生命周期是一個組件從創(chuàng)建到銷毀的整個過程苞俘;React 為生命周期提供了一些關(guān)鍵的節(jié)點窖式,本質(zhì)上是一些可以被觸發(fā)的事件港柜,以方便組件來處理各種場景
生命周期三階段 —— 1. 掛載階段【Mounting】
- 構(gòu)造函數(shù)
constructor(props, content) {}
- 組件將要加載的時候執(zhí)行的方法【也是組件渲染之前執(zhí)行的方法】
componentWillMount() {}
通過一些異步的方法可以放在componentWillMount
中執(zhí)行
- 組件加載完成執(zhí)行的方法【組件渲染完成執(zhí)行的方法】
async componentDidMount() {}
注意:所謂組件渲染就是 render 執(zhí)行完成
該方法是當(dāng)前組件接收父組件傳過來 props 的時候,會被觸發(fā)
componentWillReceiveProps(nextProps, nextContext) {
}
生命周期三階段 —— 2. 運行時階段【Updating】
主要處理的是狀態(tài)的更新引起的變化
該方法必須有一個 boolean 的返回值胳赌;該方法是用來判斷是不是應(yīng)該更新子組件
shouldComponentUpdate(nextProps, nextState, nextContext) {
return true;
}
組件將要更新牢撼,如果 shouldComponentUpdate 為 true,就會執(zhí)行 componentWillUpdate
componentWillUpdate(nextProps, nextState, nextContext) {
}
組件更新完成
componentDidUpdate(prevProps, prevState, snapshot) {
}
生命周期三階段 —— 3. 卸載階段【Updating】
我們可以在組件卸載前處理一些邏輯
組件銷毀時調(diào)用的
componentWillUnmount() {
}