一畔塔、生命周期
掛載
當(dāng)組件實(shí)例被創(chuàng)建并插入 DOM 中時(shí),其生命周期調(diào)用順序如下:
-
constructor()
如果不初始化 state 或不進(jìn)行方法綁定妨蛹,則不需要為 React 組件實(shí)現(xiàn)構(gòu)造函數(shù)。 static getDerivedStateFromProps()
-
render()
渲染頁(yè)面。 -
componentDidMount()
會(huì)在組件掛載后(插入 DOM 樹(shù)中)立即調(diào)用考阱。這里添加網(wǎng)絡(luò)請(qǐng)求和訂閱。如果添加了訂閱鞠苟,請(qǐng)不要忘記在componentWillUnmount()
里取消訂閱
注意:
下述生命周期方法即將過(guò)時(shí)乞榨,在新代碼中應(yīng)該避免使用它們:
更新
當(dāng)組件的 props 或 state 發(fā)生變化時(shí)會(huì)觸發(fā)更新。組件更新的生命周期調(diào)用順序如下:
shouldComponentUpdate()
根據(jù) shouldComponentUpdate() 的返回值当娱,決定是否執(zhí)行UNSAFE_componentWillUpdate()
吃既,render()
和componentDidUpdate()
。render()
渲染頁(yè)面跨细。componentDidUpdate()
會(huì)在更新后會(huì)被立即調(diào)用鹦倚。首次渲染不會(huì)執(zhí)行此方法。當(dāng)組件更新后冀惭,可以在此處對(duì) DOM 進(jìn)行操作震叙。如果你對(duì)更新前后的 props 進(jìn)行了比較,也可以選擇在此處進(jìn)行網(wǎng)絡(luò)請(qǐng)求云头。(例如捐友,當(dāng) props 未發(fā)生變化時(shí),則不會(huì)執(zhí)行網(wǎng)絡(luò)請(qǐng)求)溃槐。
注意:
下述方法即將過(guò)時(shí)匣砖,在新代碼中應(yīng)該避免使用它們:
卸載
當(dāng)組件從 DOM 中移除時(shí)會(huì)調(diào)用如下方法:
-
componentWillUnmount()
會(huì)在組件卸載及銷(xiāo)毀之前直接調(diào)用。在此方法中執(zhí)行必要的清理操作,例如猴鲫,清除 timer对人,取消網(wǎng)絡(luò)請(qǐng)求或清除在componentDidMount()
中創(chuàng)建的訂閱等。componentWillUnmount()
中不應(yīng)調(diào)用 setState()拂共,因?yàn)樵摻M件將永遠(yuǎn)不會(huì)重新渲染牺弄。組件實(shí)例卸載后,將永遠(yuǎn)不會(huì)再掛載它宜狐。
錯(cuò)誤處理
當(dāng)渲染過(guò)程势告,生命周期,或子組件的構(gòu)造函數(shù)中拋出錯(cuò)誤時(shí)抚恒,會(huì)調(diào)用如下方法:
組件將要掛載時(shí)觸發(fā)的函數(shù):componentWillMount
組件掛載完成時(shí)觸發(fā)的函數(shù):componentDidMount
是否要更新數(shù)據(jù)時(shí)觸發(fā)的函數(shù):shouldComponentUpdate
將要更新數(shù)據(jù)時(shí)觸發(fā)的函數(shù):componentWillUpdate
數(shù)據(jù)更新完成時(shí)觸發(fā)的函數(shù):componentDidUpdate
組件將要銷(xiāo)毀時(shí)觸發(fā)的函數(shù):componentWillUnmount
父組件中改變了props傳值時(shí)觸發(fā)的函數(shù):componentWillReceiveProps