React生命周期的变化

1、ES6语法的引入,砍掉了getDefaultProps和getInitialState

getDefaultProps 使用 static default={}的方式代替
getInitialState 使用 state属性替代,初始化可以写在constructor里,也可以写成类属性

2、下一代React版本,生命周期又有改变 

componentWillMount – 使用constructor或componentDidMount代替
componentWillUpdate – 使用componentDidUpdate代替
componentWillReceiveProps – 使用一个新的方法:static getDerivedStateFromProps来代替

React 16.3版本中:

componentWillMount,componentWillUpdate,componentWillReceiveProps还能用

React 16.x版本中:

启用弃用警告,三个方法变为:

UNSAFE_componentWillMount
UNSAFE_componentWillReceiveProps
UNSAFE_componentWillUpdate

在React17.0版本中:

会移除这三个周期。

详见https://github.com/facebook/react/issues/12152

3. static getDerivedStateFromProps

在下列三种情况下,会调用getDerivedStateFromProps方法:

1. 组件实例化。
2. 组件的props发生变化。
3. 父组件重新渲染。

this.setState()不会触发getDerivedStateFromProps(),但是this.forceUpdate()会。
在update阶段也会调用一次这个方法。

原文地址:https://www.cnblogs.com/mengff/p/9662778.html