React生命週期的變化

看風景就發表於2018-09-17

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階段也會呼叫一次這個方法。

相關文章