React1617版本生命周期汇总:
react生命周期
-
16.3/4之前的版本
- 三个阶段
- Mount(加载)
- update(更新)
- unmount(卸载)
- 生命周期
- 加载阶段
- 组件初始化state getInitialState constructor
- 组件接受props getDefaultProps componentWillRecieveProps
- 组件加载 componentWillMount
- 渲染 render
- 加载完毕 componentDidMount
- 更新阶段
- props更新
- 即将接受props componentWillRecieveProps(父组件引发渲染可能要根据props更新state)
- 是否更新页面 shouldComponentUpdate (props多了这层判断,其他和state一样)
- 组件更新前 componentWillUpdate
- 渲染 render
- 组件更新完毕 componentDidUpdate
- state 更新
- 是否更新页面 shouldComponentUpdate
- 组件更新前 componentWillUpdate
- 渲染 render
- 组件更新完毕 componentDidUpdate
- props更新
- 卸载阶段
- 卸载前 ComponentWillUnmount
- 加载阶段
- 三个阶段
-
16.3/4后的版本
随着getDerivedStateFromProps的推出,同时deprecate了一组生命周期API,包括:
- componentWillReceiveProps
- componentWillMount
- componentWillUpdate
这个生命周期函数的组合在Fiber(React Fiber是什么)之后就显得不合适了,因为,**如果要开启async rendering,在render函数之前的所有函数,都有可能被执行多次。**长期以来,原有的生命周期函数总是会诱惑开发者在render之前的生命周期函数做一些动作,现在这些动作还放在这些函数中的话,有可能会被调用多次
在Fiber启用async render之后,更没有理由在componentWillMount里做AJAX,因为componentWillMount可能会被调用多次,谁也不会希望无谓地多次调用AJAX吧。
以前需要利用被deprecate的所有生命周期函数才能实现的功能,都可以通过getDerivedStateFromProps的帮助来实现。
这个getDerivedStateFromProps是一个静态函数,所以函数体内不能访问this,简单说,就是应该一个纯函数,纯函数是一个好东西啊,输出完全由输入决定。
static getDerivedStateFromProps(nextProps, prevState) { //根据nextProps和prevState计算出预期的状态改变,返回结果会被送给setState }
每当父组件引发当前组件的渲染过程时,getDerivedStateFromProps会被调用,这样我们有一个机会可以根据新的props和之前的state来调整新的state,如果放在三个被deprecate生命周期函数中实现比较纯,没有副作用的话,基本上搬到getDerivedStateFromProps里就行了;如果不幸做了类似AJAX之类的操作,首先要反省为什么自己当初这么做,然后搬到componentDidMount或者componentDidUpdate里面去。
规则:所有被deprecate的生命周期函数,目前还凑合着用,但是只要用了,开发模式下会有红色警告,在下一个大版本(也就是React v17)更新时会彻底废弃。
强制开发者在render之前只做无副作用的操作,而且能做的操作局限在根据props和state决定新的state
新增了对错误的处理
componentDidCatch(error,info)
17版本
-
单组件生命周期
- 加载阶段
- constructor
- componentWillMount(x)
- componentWillRecieveProps(x) => getDrivedStateFromProps // 处理props转state
- render
- componentDidMount
- 更新阶段(props, state更新或者forceUpdate)
- getDrivedStateFromProps
- shouldComponentUpdate
- render
- componentWillUpdate(x) => getSnapshotBeforeUpdate // 处理更新前的数据
- update dom
- componentDidUpdate // 请求数据
- 卸载阶段
- componentWillUnmount 清理事件
- 加载阶段
-
父子组件生命周期
-
挂载:
父组件componentWillMount->子父组件componentWillMount->子组件componentDidMont->父组件componentDidMount
-
更新:
-
更新父组件或者父子同时更新
父组件shoulComponentUpdate->子componentWillUpdate->子componentWillReceiveProps->子shouldComponentUpdate->子componentWillUpdate->子componentDidUpdate->父组件componentDidUpdate
-
只更新子组件
子组件shouldComponentUpdate->子componentWillUpdate->子componentDidUpdate
-
-
销毁:
父组件componentWillUnmount->子组件componentWillUnmount
-
-
16-17对比
主要还是更新阶段的不同,需要注意下。