react新版本生命週期

2022-08-09 04:03:12 字數 2868 閱讀 5754

給componentwillmount componentwillreceiveprops componentwillupdate生命週期加上unsafe_字首,表明其不安全性,並將在未來版本將其移除

官網文件指出使用這些生命週期的**會在未來版本的react中更容易產生bug,尤其是對於非同步渲染的版本

新增生命週期static getderivedstatefromprops(prevprops, prevstate)、getsnapshotbeforeupdate(prevprops, prevstate) 、componenddidcatch(error, info)

static getderivedstatefromprops(prevprops, prevstate)

在每次渲染之前都會呼叫,不管造成重新渲染的原因,不管初始掛載還是後面的更新都會呼叫,這一點和unsafe_componentwillreceiveprops不同(只有當父元件造成重新渲染時才呼叫),每次都應該返回乙個物件作為state的更新,或者返回null表示不更新

它的使用場景一般為依賴於props的變化去做一些狀態的更新,讓我們能夠根據props的變化去更新內部的狀態,以前我們經常在componentwillreceiveprops中完成該操作

但是你需要考慮是否真的有必要使用這個生命週期,比如:

如果你需要根據網路請求獲取資料,你可以在componentdidupdate裡完成

當props改變時,你需要去重新計算某些資料,可以使用memoization helper替代

當props改變時,如果你想要重置一些state,可以考慮使用fully controlled component(完全移出state的使用,通過父元件控制資料)或者fully uncontrolled component(資料僅存在內部狀態中)

getsnapshotbeforeupdate(prevprops,prevstate)

在最新的渲染資料提交給dom前會立即呼叫,它讓你在元件的資料可能要改變之前獲取他們,他的返回值會被傳遞給componentdidupdate的第三個引數

componentdidcatch

如果乙個元件定義了componentdidcatch生命週期,則他將成為乙個錯誤邊界(錯誤邊界會捕捉渲染期間、在生命週期方法中和在它們之下整棵樹的建構函式中的錯誤,就像使用了try

catch,不會將錯誤直接丟擲了,保證應用的可用性)

class a extends react.component 

// 用於替換 `componentwillreceiveprops` ,該函式會在初始化和 `update` 時被呼叫

// 因為該函式是靜態函式,所以取不到 `this`

// 如果需要對比 `prevprops` 需要單獨在 `state` 中維護

static getderivedstatefromprops(nextprops, prevstate) {}

// 判斷是否需要更新元件,多用於元件效能優化

shouldcomponentupdate(nextprops, nextstate) {}

// 元件掛載後呼叫

// 可以在該函式中進行請求或者訂閱

componentdidmount() {}

// 用於獲得最新的 dom 資料

getsnapshotbeforeupdate() {}

// 元件即將銷毀

// 可以在此處移除訂閱,定時器等等

componentwillunmount() {}

// 元件銷毀後呼叫

componentdidunmount() {}

// 元件更新後呼叫

componentdidupdate() {}

// 渲染元件函式

render() {}

// 以下函式不建議使用

unsafe_componentwillmount() {}

unsafe_componentwillupdate(nextprops, nextstate) {}

unsafe_componentwillreceiveprops(nextprops) {}

}

getderivedstatefromprops內部不可以有***,因為現在是無論是state改變還是props改變,都會執行它。例如:這種寫法會導致多次迴圈渲染直到報錯

constructor(props);

}static getderivedstatefromprops(props, state) ;

}return null;

} myfetch())

} render() div>

);}}

以上正確寫法應為:

constructor(props);

} // 純函式,無***

static getderivedstatefromprops(props, state) ;

}return null;

} componentdidupdate()

} // 看是否需要初始化的時候呼叫

componentdidmount()

myfetch())

} render() div>

);}}

React各個版本生命週期和作用

15版本 初始化階段 getdefaultprops 作用 該階段主要是定義初始化props 寫法 getdefaultprops getinitstate作用 該階段主要是初始化state 寫法 getinitstate 小總結 這2個鉤子也是15版本和16版本的區別之一 16版本 更新階段 1....

React 生命週期 生命週期方法

生命週期 掛載 更新 解除安裝 元件被建立 執行初始化 並被掛載到dom中,完成元件的第一次渲染 constructor props getderivedstatefromprops props,state render componentdidmount 元件被建立時會首先呼叫元件的構造方法,接受...

react新舊版本生命週期函式講解

react在引入 fiber 之後,其生命週期也有所變化,新增了一些生命週期函式,同時也建議使用者廢棄一些生命週期函式,下面博主對比一下react v16.3之前的生命週期與react v16.4及之後的生命週期函式。當元件的 props 或 state 發生變化時會觸發更新。元件更新的生命週期呼叫...