在舊版本的react中(16.9)一下的版本中react的生命周期分為:
constructor/(getDefaultProps橙依、getInitialState):使用class的方式創(chuàng)建使用static defaultProps = {}定義組件屬性的默認值博敬,constructor初始化組件狀態(tài)昭娩;使用creatClass的方法創(chuàng)建組件理卑,使用getDefaultProps定義組件屬性值的默認值饲梭,使用geInitialState初始化組件的狀態(tài)
componentWillMount:組件渲染前執(zhí)行
componentDidMount:組件渲染后執(zhí)行
componentWillReceiveProps:組件接收到新的屬性后執(zhí)行
shouldComponentUpdate:在確定組件需要更新门驾,并準備去更新前執(zhí)行充包,返回false則不更新組件
componentWillUpdate:組件更新前執(zhí)行
componentDidUpdate:組件更新后執(zhí)行
componentWillUnmount:組件卸載之前執(zhí)行
在新版本中這些生命周期函數(shù)有一些改動位谋,首先新版本棄用了componentWillMount山析、componentWillReceivePorps,componentWillUpdate這三個生命周期掏父,非要使用也是可以的但是在使用過程中會報一個“has been renamed”的警告笋轨,這個時候有以下解決辦法:
1.在報警告的生命周期函數(shù)前面加上前綴“UNSAFE_”,這個據(jù)說有插件可以完成
2.降低react和react-dom的版本到16.9一下赊淑,推薦使用16.4.1這個版本
3.使用react提供的新的生命周期函數(shù)替代
這里著重說第三種方式:
在新版本的react中提供了兩個新的生命周期函數(shù)爵政,getDerivedStateFromProps,getSnapshotBeforeUpdate來代替componentWillMount陶缺、componentWillReceivePorps钾挟,componentWillUpdate這三個生命周期函數(shù),這兩個版本的生命周期函數(shù)不能混用饱岸,并且getDerivedStateFromProps這個函數(shù)必須返回一個state掺出,不然同樣報錯;
同時新增了componentDidCatch和static getDerivedStateFromError兩個處理錯誤的方法伶贰,當渲染過程蛛砰,生命周期,或子組件的構(gòu)造函數(shù)中拋出錯誤時黍衙,會調(diào)用兩個方法泥畅;
并且新增了一個forceUpdate的api,這個api可以強制組件重新渲染琅翻,直接調(diào)用組件的render方法位仁,所以如果是更新操作中使用了這個api的話柑贞,會阻斷更新操作,去強制重新渲染組件
getDerivedStateFromProps:componentWillMount和componentWillReceviceProps的組件聂抢;當組件構(gòu)建完成之后掛載渲染之前會調(diào)用钧嘶;當接收到新的prop和state時會調(diào)用;每次接受到props后都要返回一個對象作為新的state琳疏,如果返回null則說明不需要更新state
getSnapshotBeforeUpdate:替代了componentWillUpdate的功能有决,接收參數(shù)是舊的props和舊的state;此生命周期函數(shù)的任何返回值空盼,將作為參數(shù)傳遞給componentDidUpdate书幕,作為componentDidUpdate的除了preProps和preState以外的參數(shù);shouldComponentUpdate返回false后將不執(zhí)行
static getDerivedStateFromError:在后代組件拋出異忱恐海或錯誤時觸發(fā)台汇,接收拋出的錯誤作為參數(shù),并返回一個值用來更新state
componentDidCatch:在后代組件拋出異忱橄梗或錯誤時觸發(fā)苟呐,接收拋出的錯誤和異常組件的棧信息作為參數(shù)