getDerivedStateFromProps
getDerivedStateFromProps
的作用是為了讓 props
能更新到組件內(nèi)部 state
中儡炼。他會在render
方法之前調(diào)用妓湘,并且在初始掛載及后續(xù)更新時都會被調(diào)用。它應(yīng)返回一個對象來更新 state
乌询,如果返回 null
則不更新任何內(nèi)容榜贴。但注意在沒有內(nèi)容更新的情況下也一定要返回一個null
值。不然會報錯妹田。
這個生命周期的意思就是從props中獲取state唬党,這個生命周期替換了原有的生命周期函數(shù)componentWillReceiveProps
,getDerivedStateFromProps
,它
是一個靜態(tài)函數(shù)鹃共,也就是說不能通過this來訪問class的屬性,也不推薦直接訪問屬性驶拱。而是通過參數(shù)提供的nextPros
以及prevState
來進(jìn)行判斷霜浴,根據(jù)新傳入的props
來映射state
。
注意:如果傳入的props不影響state蓝纲,則必須返回一個null阴孟,一般盡量寫在末尾。
static getDerivedStateFromProps(nextProps,prevState){
// state無更新時return null
return null;
}
在使用此生命周期時税迷,要注意把傳入的 props
值和之前傳入的 props
進(jìn)行比較