React的生命周期
在React 15.x版本或者之前的版本,生命周期只有三個階段
在React 16.3之后新增了一個;有12個鈎子函數,四個階段分別為:初始化,運行中,銷毀,錯誤處理
組件從創建到銷毀的過程被稱為組件的生命周期,通常分為三個階段:掛載階段,更新階段,卸載階段
Mounting: constructor -> render -> (React updates dom and refs) -> componentDidMount
Updating: (newProps setState() forceUpdate()) -> componentDidUpdate
Unmounting: componentWillUnMount
一、掛載階段
-
constructor,初始化state和綁定事件處理方法
-
componentWillMount,組件即將掛載,只調用一次(已廢棄)
-
render,定義組件,是一個純函數:
1.計算this.props/this.state返回的對應結果
2.通過React.createElement將jsx轉換為VDOM對象模型 -
componentDidMount,在組件被掛載到Dom后調用,只調用一次,這個時候已經可以獲取到dom結構
二、更新階段
- componentWillReceviesProps(nextProps),只會在props引起的組件更新時候調用(已廢除)
- shouldComponentUpdate(nextProps,nextState),通過返回true跟false來決定組件是否更新,在這里不能調用setState,會引起循環調用
- componentWillUpdate(nextProps,nextState),組件更新前,在這里不能調用setState,會引起循環調用(已廢除)
- componentDidUpate(prevProps,prevState)
三、卸載階段
- componentWillUnmount
四、錯誤處理階段
- componentDidCatch(err,info)
新的生命周期廢除了原來的 componentWillMount componentWillReceviesProps componentWillUpdate,新增了static getDerivedStateFromProps getSnapshotBeforeUpdate
舊的生命周期:
初始化;
Mounting:componentWillMount render componentDidMount
Updating:
props 更新: componentReceiveProps shouldComponentUpdate
如果 shouldComponent 返回true, componentWillUpdate render componentDidUpdate
state 更新: shouldComponentUpdate
如果 shouldComponentUpdate 返回true, componentWillUpdate render componentDidUpdate
Unmounting:componentWillUnmount;
新的生命周期:
Mounting:constructor getDerivedStateFromProps render componentDidMount
Updating:
props 更新: getDerivedStateFromProps shouldComponentUpdate
如果 shouldComponent 返回true, render getSnapshotBeforeUpdate componentDidUpdate
state 更新: shouldComponentUpdate
如果 shouldComponentUpdate 返回true, render getSnapshotBeforeUpdate componentDidUpdate
force update: render getSnapshotBeforeUdate componentDidUpdate
Unmounting: componentWillMount
被廢棄的三個函數都是在render之前,因為fiber的出現,很可能因為高優先級任務的出現打斷現有任務導致它們被執行多次
-
1) componentWillMount,可用constructor+componentDidMount代替
-
2) componentWillReceviesProps,會破壞state數據的單一數據源,導致組件狀態不好預測,還會增加重繪次數,用getDerivedStateFromProps替代
-
3) getDerivedStateFromProps(nextProps,prevState);
componentWillReceviesProps(nextProps){
if(nextProps.xxx!==this.props.xxx){
this.setState({
xxx: nextProps.xxx
})
};
this.xxx();
}
對比
static getDerivedStateFromProps(nextProps,prevState){
if(nextProps.xxx!==prevState.xxx){
return {
xxx : nextProps.xxx
}
}
}
componentDidUpdate(prevProps,prevState){
this.xxx()
}
-
- componentWillUpdate,用getSnapshotBeforeUpdate(prevProps,prevState)返回的值作為componentDidUpdate第三個參數;componentDidUpdate(prevProps,prevState,snap)
-
- getSnapshotBeforeUpdate會在最終確定的render執行之前執行,能保證到跟componentDidUpdate的元素狀態相同