React 16.3之前
对React生命周期的理解
1、getDefaultProps()
设置默认的props,也可以用dufaultProps设置组件的默认属性.

2、getInitialState()
在使用es6的class语法时是没有这个钩子函数的,可以直接在constructor中定义this.state。此时可以访问this.props

3、componentWillMount()
组件初始化时只调用,以后组件更新不调用,整个生命周期只调用一次,此时可以修改state。

4、 render()
react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行。此时就不能更改state了。

5、componentDidMount()
组件渲染之后调用,只调用一次。

更新
6、componentWillReceiveProps(nextProps)
组件初始化时不调用,组件接受新的props时调用。

7、shouldComponentUpdate(nextProps, nextState)
react性能优化非常重要的一环。组件接受新的state或者props时调用,我们可以设置在此对比前后两个props和state是否相同,如果相同则返回false阻止更新,因为相同的属性状态一定会生成相同的dom树,这样就不需要创造新的dom树和旧的dom树进行diff算法对比,节省大量性能,尤其是在dom结构复杂的时候

8、componentWillUpdata(nextProps, nextState)
组件初始化时不调用,只有在组件将要更新时才调用,此时可以修改state,但是不能调用this.setState

9、render()
组件渲染

10、componentDidUpdate()
组件初始化时不调用,组件更新完成后调用,此时可以获取dom节点。

卸载
11、componentWillUnmount()
组件将要卸载时调用,一些事件监听和定时器需要在此时清除。

React16.3之后
对React生命周期的理解
最大的变动莫过于生命周期去掉了以下三个
componentWillMount
componentWillReceiveProps
componentWillUpdate

同时为了弥补失去上面三个周期的不足又加了两个
static getDerivedStateFromProps
getSnapshotBeforeUpdate
当然,这个更替是缓慢的,在整个16版本里都能无障碍的使用旧的三生命周期,但值得注意的是,旧的生命周期(unsafe)不能和新的生命周期同时出现在一个组件,否则会报错“你使用了一个不安全的生命周期”。

static getDerivedStateFromProps
会在初始化和update时触发,用于替换componentWillReceiveProps,可以用来控制 props 更新 state 的过程;它返回一个对象表示新的 state;如果不需要更新,返回 null 即可
getSnapshotBeforeUpdate
用于替换 componentWillUpdate,该函数会在update后 DOM 更新前被调用,用于读取最新的 DOM 数据,返回值将作为 componentDidUpdate 的第三个参数

相关文章:

  • 2021-12-12
  • 2021-04-14
猜你喜欢
  • 2021-08-15
  • 2022-01-08
  • 2021-08-19
  • 2021-11-22
  • 2021-12-07
  • 2021-10-05
  • 2021-04-07
相关资源
相似解决方案