背景
我们公司前端组从 2017 年 1 月份全面转战 React 以来,使用 React 15 开发至今,随着业务地不断增加,项目体量也在不断升级,我们在性能方面碰到了一些瓶颈(比如展示非常多条记录的表格)。React 16 的推出以及它即将应用升级的全新的 fiber 架构使我们看到了一些很 hack 的解决方案(关于 fiber 架构就不在此篇文章当中进一步展开)。早在 2017 年 9 月份,React 就已然推出了 16.0,至今已经发布到了 16.3.1 版本。众多相关库纷纷响应起来,而其中就有我们项目中用得最广泛的 React UI 组件库 antd。antd 3.0 以及 antd pro 的推出也进一步促使了我们把公司现行项目升级到 React 16.x 的决心。
阅读官方文档
建议有时间的话把官方文档中 Docs、Blog 这两个模块的内容都阅读一遍,有助于理解。要是英文影响阅读速度,可尝试通过第三方中文文档网站阅读。
16.0~16.3 官方升级日志
16.0:https://reactjs.org/blog/2017/09/26/react-v16.0.html
16.2:https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
16.3:https://reactjs.org/blog/2018/03/29/react-v-16-3.html
重要新特性
Fragments:https://reactjs.org/docs/fragments.html
Render Props:https://reactjs.org/docs/render-props.html
错误采集:https://reactjs.org/docs/error-boundaries.html
new Context API:https://reactjs.org/docs/context.html
new Refs way: https://reactjs.org/docs/refs-and-the-dom.html
Portals API: https://reactjs.org/docs/portals.html
值得一看
React 16 新生命周期指南:https://reactjs.org/docs/react-component.html
展望 React 16:https://reactjs.org/blog/2018/03/01/sneak-peek-beyond-react-16.html
关于异步渲染:https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
一些重要的点
React.PropTypes 分包
1 | // Before |
不安全的生命周期函数
• 16.3: Introduce aliases for the unsafe lifecycles, UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, and UNSAFE_componentWillUpdate. (Both the old lifecycle names and the new aliases will work in this release.)
• A future 16.x release: Enable deprecation warning for componentWillMount, componentWillReceiveProps, and componentWillUpdate. (Both the old lifecycle names and the new aliases will work in this release, but the old names will log a DEV-mode warning.)
• 17.0: Remove componentWillMount, componentWillReceiveProps, and componentWillUpdate . (Only the new “UNSAFE_” lifecycle names will work from this point forward.)
16.3 新增的生命周期函数static getDerivedStateFromProps and getSnapshotBeforeUpdateFragment 语法糖 <></> 需要编译支持
升级评估
依赖包引用方式
有破坏性升级,原 React.PropTypes 被提到 prop-types 包
生命周期
无破坏性升级,兼容原来的生命周期并提供两个新的生命周期函数 static getDerivedStateFromProps and getSnapshotBeforeUpdate
Fragement 新特性
需要升级 babel 以及 Eslint 来支持,目前支持 React 16 的仍处于 beta 阶段,但稳定版即将推出
升级进行时
第一关:React.PropTypes 改为单独引用
第二关:mobx-react 报错
需要升级 mobx-react 到 v4.4.3,如果升级至 v5.0.0 会要求需要升级 mobx 大版本至 v4.x,暂时只升级至 v4.4.3
第三关:升级 babel.beta 来支持 Fragement 空标签特性
babel v7 以后所有包命名都加上了 @babel 前缀,比如 babel-core ==> @babel/core。而 babel-loader 依赖最新稳定版本依赖的仍然是旧命名,作者在发布了 v7 以后,为了适应 babel v7 在 babel-loader v7 的基础上,直接升级大版本 v8.beta。v8.beta 支持更正为最新命名
第四关:升级了 @babel/core、@babel/prset-react、babel-loader 后编译碰到错误
看起来应该是要把 babel 下的所有其它包以及配置也同时升级。鉴于当下所有 babel 相关的包处于 beta 阶段,建议过一段时间等稳定版本发布了并有一些人踩了坑之后再尝试支持【空标签】的新特性,官方也支持我们先通过 <Fragement> 标签化的形式,后续再替换为空标签的语法糖
This is copyright.