React V16.x 生命周期调整

  • 旧声明周期:
生命周期属于阶段调用次数是否可以setState作用
getDefaultProps创建阶段(Mounting)1次(全局调用1次)不可以
getInitialState创建阶段(Mounting)1次不可以
componetWillMount创建阶段(Mounting)1次可以;不会触发 re-render
render创建阶段(Mounting) 和 更新阶段(Updating)>=1次不可以
componentDidMount创建阶段(Mounting)1次可以;触发re-render,影响性能
componetWillReceiveProps更新阶段(Updating)>=0可以
shouldComponentUpdate更新阶段(Updating)>=0不可以该方法通过返回 true 或者 false 来确定是否需要触发新的渲染。返回 false, 则不会触发后续的 UNSAFE_componentWillUpdate()、render() 和 componentDidUpdate()(但是 state 变化还是可能引起子组件重新渲染)。
componentWillUpdate更新阶段(Updating)>=0不可以
componentDidUpdate更新阶段(Updating)>=0可以;触发re-render,影响性能
componentWillUnmount卸载阶段(Unmounting)1次不可以
  • 新声明周期:
生命周期属于阶段是否可以setState作用
constructor()创建阶段 Mounting注意:ES6 子类的构造函数必须执行一次 super()。React 如果构造函数中要使用 this.props,必须先执行 super(props)。
getDerivedStateFromProps当创建时、接收新的 props 时、setState 时、forceUpdate 时会执行注意:v16.3 版本 setState、forceUpdate 时不会执行这个方法,v16.4 版本修复了这个问题。
  • 逐渐废弃的生命周期方法(3个Will):
componentWillMount()
componentWillReceiveProps()
componentWillUpdate()

虽然废弃了这三个生命周期方法,但是为了向下兼容,将会做渐进式调整。

V16.3 并未删除这三个生命周期,同时还为它们新增以 UNSAFE_ 前缀为别名的三个函数 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()。

在 16.4 版本给出警告将会弃用 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 三个函数

然后在 17 版本将会删除 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 这三个函数,会保留使用 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()