constructor
getDerivedStateFromProps
~~componentWillMount/UNSAVE_componentWillMount~~
render
componentDidMount(第一次render以後執行)
props
或 state
發生變化時會觸發更新。組件更新的生命週期調用順序以下:static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
DOM
中移除時會調用以下方法:componentWillUnmount()
~~componentWillMount~~
~~componentWillReceivePorps~~
~~componentWillUpdate~~
getDerivedStateFromProps
(能夠用來替換componentWillReceiveProps()
)props
更新state
上的meuns
// 這個方法已經不建議使用
componentWillReceiveProps(next){
this.setState({
menus:next.role.menus
})
}
複製代碼
static getDerivedStateFromProps(nextProps, prevState){
if (nextProps.role.menus !== prevState.menus) {
// 額外寫一個newMeuns state來記錄上一個props,在組件渲染的時候傳入這個更新後的newMeuns
return {
newMenus:nextProps.role.menus
};
}
// 不更新state
return null
}
複製代碼
getSnapshotBeforeUpdate()
(在最近一次渲染輸出(提交到 DOM
節點)以前,render
以後調用)props
也會調用componentWillReceivePorps
componentWillUpdate、componentDidUpdate
之間的時間變長,這個過程當中可能發生一些變化,好比用戶行爲致使 DOM 發生了新的變化,這時在 componentWillUpdate
獲取的信息可能就不可靠了static getDerivedStateFromProps(nextProps, prevState)
接收兩個參數(它內部你只能訪問到組件上的這兩個參數),第一個爲接收到的新參數,第二是是當前的state
。會返回一個對象用來更新state
不須要能夠返回null
class Hehe extends React.Component {
state={
isRight:false,
xxx:xxx
}
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.xxx===prevState.xxx){
return {
isRight:true
}
}
return null
}
}
複製代碼
React
⼏個版本(1.6.三、1.6.四、1.7.0)對⽣命週期的相關處理和規劃?getDerivedStateFromProps
設計爲靜態⽅法?getDerivedStateFromProps
被觸發執⾏的條件有哪些?props
時state
能夠總結爲一句話,此靜態方法會在render
以前被調用,在初始掛載以及後續更新的時候都會被調用。Derived state
的定義是?(如何理解derived state
?)派生一個state,根據傳入的props進行state的更新react
setState()
不會引發getDerivedFromProps
的執⾏,⽽1.6.4.會,緣由是?聽說是官方失誤bash
雖然廢棄了這三個生命週期方法,可是爲了向下兼容,將會作漸進式調整。 V16.3 並未刪除這三個生命週期,同時還爲它們新增以 UNSAFE_ 前綴爲別名的三個函數 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()。 在 16.4 版本給出警告將會棄用 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 三個函數異步