React的组件生命周期
- 1. 掛載卸載過程
- 1.1.constructor()
- 1.2.componentWillMount()
- 1.3.componentDidMount()
- 1.4.componentWillUnmount ()
- 2. 更新過程
- 2.1. componentWillReceiveProps (nextProps)
- 2.2.shouldComponentUpdate(nextProps,nextState)
- 2.3.componentWillUpdate (nextProps,nextState)
- 2.4.componentDidUpdate(prevProps,prevState)
- 2.5.render()
- 3. React新增的生命周期(個人補充)
- 3.1. getDerivedStateFromProps(nextProps, prevState)
- 3.2. getSnapshotBeforeUpdate(prevProps, prevState)
這周開始學(xué)習(xí)React的生命周期。
React的生命周期從廣義上分為三個階段:掛載、渲染、卸載
因此可以把React的生命周期分為兩類:掛載卸載過程和更新過程。
React的生命周期圖:
1. 掛載卸載過程
1.1.constructor()
constructor()中完成了React數(shù)據(jù)的初始化,它接受兩個參數(shù):props和context,當想在函數(shù)內(nèi)部使用這兩個參數(shù)時,需使用super()傳入這兩個參數(shù)。
注意:只要使用了constructor()就必須寫super(),否則會導(dǎo)致this指向錯誤。
1.2.componentWillMount()
componentWillMount()一般用的比較少,它更多的是在服務(wù)端渲染時使用。它代表的過程是組件已經(jīng)經(jīng)歷了constructor()初始化數(shù)據(jù)后,但是還未渲染DOM時。
1.3.componentDidMount()
組件第一次渲染完成,此時dom節(jié)點已經(jīng)生成,可以在這里調(diào)用ajax請求,返回數(shù)據(jù)setState后組件會重新渲染
1.4.componentWillUnmount ()
在此處完成組件的卸載和數(shù)據(jù)的銷毀。
原因:因為你在組件中的ajax請求返回setState,而你組件銷毀的時候,請求還未完成,因此會報warning
解決方法:
2. 更新過程
2.1. componentWillReceiveProps (nextProps)
2.2.shouldComponentUpdate(nextProps,nextState)
2.3.componentWillUpdate (nextProps,nextState)
shouldComponentUpdate返回true以后,組件進入重新渲染的流程,進入componentWillUpdate,這里同樣可以拿到nextProps和nextState。
2.4.componentDidUpdate(prevProps,prevState)
組件更新完畢后,react只會在第一次初始化成功會進入componentDidmount,之后每次重新渲染后都會進入這個生命周期,這里可以拿到prevProps和prevState,即更新前的props和state。
2.5.render()
render函數(shù)會插入jsx生成的dom結(jié)構(gòu),react會生成一份虛擬dom樹,在每一次組件更新時,在此react會通過其diff算法比較更新前后的新舊DOM樹,比較以后,找到最小的有差異的DOM節(jié)點,并重新渲染。
3. React新增的生命周期(個人補充)
React新增生命周期
?
3.1. getDerivedStateFromProps(nextProps, prevState)
代替componentWillReceiveProps()。老版本中的componentWillReceiveProps()方法判斷前后兩個 props 是否相同,如果不同再將新的 props 更新到相應(yīng)的 state 上去。這樣做一來會破壞 state 數(shù)據(jù)的單一數(shù)據(jù)源,導(dǎo)致組件狀態(tài)變得不可預(yù)測,另一方面也會增加組件的重繪次數(shù)。
舉個例子:
這兩者最大的不同就是:在 componentWillReceiveProps 中,我們一般會做以下兩件事,一是根據(jù) props 來更新 state,二是觸發(fā)一些回調(diào),如動畫或頁面跳轉(zhuǎn)等。
3.2. getSnapshotBeforeUpdate(prevProps, prevState)
代替componentWillUpdate。常見的 componentWillUpdate 的用例是在組件更新前,讀取當前某個 DOM 元素的狀態(tài),并在 componentDidUpdate 中進行相應(yīng)的處理。
這兩者的區(qū)別在于:
componentDidUpdate 中使用 componentWillUpdate 中讀取到的 DOM 元素狀態(tài)是不安全的,因為這時的值很有可能已經(jīng)失效了。
此生命周期返回的任何值都將作為參數(shù)傳遞給componentDidUpdate()。
總結(jié)
以上是生活随笔為你收集整理的React的组件生命周期的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。