【一起來學React】- 16版本中生命週期的使用及建議
阿新 • • 發佈:2018-12-26
在 V16 版本中引入了 Fiber 機制。這個機制一定程度上的影響了部分生命週期的呼叫,下面是個人使用的一點建議和心得!
文章首發:https://www.fakin.cn/2469.html
React渲染有兩個階段:reconciliation 和 commit 。前者過程是可以被打斷的,後者則不能有任何的暫停,會一直更新介面直到完成。
Reconciliation 階段
componentWillMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
Commit 階段
componentDidMount
omponentDidUpdate
componentWillUnmount
其實很好理解,看名字都知道will是即將,肯定能打斷撒,舉個例子,
componentWillReceiveProps,在使用的時候,你有沒有遇到過,會執行兩次或多次的bug?
所以v16中Reconciliation階段建議除了shouldComponentUpdate以外其他的能不用就不要用。
V16生命週期使用建議
getDerivedStateFromProps 用於替換 componentWillReceiveProps ,該函式會在初始化和 update 時被呼叫,getSnapshotBeforeUpdate 用於替換 componentWillUpdate ,該函式會在 update 後 DOM 更新前被呼叫,用於讀取最新的 DOM 資料。
class Fakin extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {}//替換componentWillReceiveProps
shouldComponentUpdate(nextProps, nextState) {}//是否更新
componentDidMount() {}//元件被掛載
getSnapshotBeforeUpdate(){}//替換componentWillUpdate 用於獲得最新的 DOM 資料
componentWillUnmount( ) {}//元件即將被銷燬
componentDidUpdate() {}//元件已經更新
render() {}//渲染函式
}
需要注意的是getDerivedStateFromProps是靜態方法。