前言
學(xué)習(xí)過(guò)React的同學(xué)應(yīng)該知道react生命周期函數(shù)貫穿于數(shù)組的初始化、掛載、更新、銷(xiāo)毀的整個(gè)過(guò)程。可以說(shuō)配合緊密,但是隨著react使用的深入,在業(yè)務(wù)開(kāi)發(fā)中一些聲明的周期函數(shù)也會(huì)帶一些嚴(yán)重的問(wèn)題,因此官方也很快做出了修正,廢棄了幾個(gè)容易造成嚴(yán)重問(wèn)題的函數(shù),并且給出來(lái)代替的函數(shù)。
react精益求精的“棄子”
- 1.componentWillMount
- 2.componentWillUpdate
- 3.componentWillReceiveProps
原因
在componentWillMount進(jìn)行異步請(qǐng)求,能使數(shù)據(jù)返回的更快。但,componentWillMount結(jié)束后,render會(huì)立即被觸發(fā),但此時(shí)componentWillMount中的異步請(qǐng)求結(jié)果可能還未返回。一旦結(jié)果返回就會(huì)重新render,所以說(shuō)即使在componentWillMount 就進(jìn)行了異步請(qǐng)求,在返回?cái)?shù)據(jù)后又會(huì)重新render,這會(huì)導(dǎo)致服務(wù)端渲染場(chǎng)景下的冗余請(qǐng)求等額外問(wèn)題。得不償失,因此在componentDidMount來(lái)請(qǐng)求沒(méi)太大的差別,所以官方將它廢除了。
假如你在compoentWillMount中發(fā)起了一個(gè)付款請(qǐng)求,由于render階段里的生命周期都可以重復(fù)執(zhí)行,在componentWillMount被打斷 + 重啟多次后,就會(huì)發(fā)出多個(gè)付款請(qǐng)求。
或者你可能習(xí)慣在 componentWillReceiveProps (在已掛載的組件接收到props之前被調(diào)用)里操作DOM(比如刪除某個(gè)符合特征的元素),那么componentWillReceiveProps 若是執(zhí)行了兩次,你可能就會(huì)一口氣刪掉兩個(gè)符合特征的元素。
假如在 compoenntWillReceiveProps 和 compoentWillUpdate 里濫用setState 將導(dǎo)致重復(fù)渲染死循環(huán)。
新生命周期函數(shù)
constructor()
static getDerivedStateFromProps(props,state)
shouldComponetUpdate()
render()
componentDidMount()
static getSnapshotBeforeUpdate(prevprops,prevState)
componentDidUpdate()
componentWillUnmount()
掛載前順序
constructor()
static getDerivedStateFromProps(props,state)
render()
掛載后
componentDidMount()
更新前順序
static getSnapshotBeforeUpdate(prevprops,prevState)
shouldComponentUpdate()
render()
更新后順序
static getSnapshotBeforeUpdate(prevprops,prevState)
componentDidMount()
卸載
componetWillUnmount()
現(xiàn)版本廢棄的生命周期鉤子函數(shù)

文章轉(zhuǎn)自 http://www.itdecent.cn/p/13b62e814a04