React生命週期中的Updation階段,也就是組件發生改變的更新階段,這是React生命週期中比較複雜的一部分,它有兩個基本部分組成,一個是props屬性改變,一個是state狀態改變(這個在生命週期的圖片中可以清楚的看到)。
16.4之後版本聲明週期圖,
圖紙來源:https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
componentWillReceiveProps 函數
寫在頂層組件沒有接收props屬性是不執行的 ,要寫在接收props屬性的組件中
子組件接收到父組件傳遞過來的參數,父組件render函數重新被執行,這個生命週期就會被執行。
組件第一次存在於dom中,函數不會執行 第一次渲染
如果已經存在dom中,函數再會執行(第二次發生變化)
16.4之前版本
componentWillReceiveProps(){
console.log("componentWillReceiveProps")
}
16.4之後版本 掛載跟 父組件更新都會觸發此 生命週期
static getDerivedStateFromProps(props, state){
//
console.log(props,state)
return state;
}
下面是組件的state或者props 改變 觸發的生命週期
shouldComponentUpdate
版本跟新前後無變化
函數會在組件更新之前,自動被執行,會在render 渲染之前執行
它要求返回一個布爾類型的結果,必須有返回值,false 下面的代碼就不再執行
shouldComponentUpdate(nextProps, nextState){
console.log(1,'shouldComponentUpdate');
return true;
}
即將更新組件,shouldComponentUpdate之後 執行
16.4以前版本
componentWillUpdate(){
console.log('componentWillUpdate')
// true/false 同上
return true
}
16.4以後版本
UNSAFE_componentWillUpdate(nextProps, nextState){
console.log(2,"即將更新組件");
}
render 這裏不再解釋,使用render必須要帶上的
完成渲染即將被掛載在DOM中, 這會已經生成了新的DOM節點了,不過還有修改文檔,你可以在這裏去獲取更新之前的文檔
16.4之前無此聲明週期
getSnapshotBeforeUpdate(prevProps, prevState){
console.log(4,'getSnapshotBeforeUpdate');
return 123;
}
更新完成之後 render之後 執行的函數
無版本變化
componentDidUpdate(){
console.log('5-componentDidUpdate')
}
組件被刪除/卸載之前 執行
componentWillUnmount(){
console.log("componentWillUnmount")
}
結合圖示思路會更加清晰了