react 組件生命周期

實(shí)例化

首次實(shí)例化
   getDefaultProps
   getInitialState
   componentWillMount
   render
   componentDidMount
   實(shí)例化完成后的更新
   getInitialState
   componentWillMount
   render
   componentDidMount

存在期

  組件已存在時(shí)的狀態(tài)改變
     componentWillReceiveProps
     shouldComponentUpdate
     componentWillUpdate
     render
    componentDidUpdate

銷毀&清理期

   componentWillUnmount

說明

生命周期共提供了10個(gè)不同的API。
1.getDefaultProps
作用于組件類,只調(diào)用一次,返回對(duì)象用于設(shè)置默認(rèn)的props,對(duì)于引用值,會(huì)在實(shí)例中共享。
2.getInitialState
作用于組件的實(shí)例,在實(shí)例創(chuàng)建時(shí)調(diào)用一次,用于初始化每個(gè)實(shí)例的state,此時(shí)可以訪問this.props。
3.componentWillMount
在完成首次渲染之前調(diào)用,此時(shí)仍可以修改組件的state。
4.render
必選的方法,創(chuàng)建虛擬DOM,該方法具有特殊的規(guī)則:
只能通過this.props和this.state訪問數(shù)據(jù)
可以返回null、false或任何React組件
只能出現(xiàn)一個(gè)頂級(jí)組件(不能返回?cái)?shù)組)
不能改變組件的狀態(tài)
不能修改DOM的輸出
5.componentDidMount
真實(shí)的DOM被渲染出來后調(diào)用,在該方法中可通過this.getDOMNode()訪問到真實(shí)的DOM元素。此時(shí)已可以使用其他類庫來操作這個(gè)DOM。
在服務(wù)端中,該方法不會(huì)被調(diào)用。
6.componentWillReceiveProps
組件接收到新的props時(shí)調(diào)用,并將其作為參數(shù)nextProps使用,此時(shí)可以更改組件props及state。
componentWillReceiveProps: function(nextProps) {
if (nextProps.bool) {
this.setState({
bool: true
});
}
}
7.shouldComponentUpdate
組件是否應(yīng)當(dāng)渲染新的props或state,返回false表示跳過后續(xù)的生命周期方法,通常不需要使用以避免出現(xiàn)bug。在出現(xiàn)應(yīng)用的瓶頸時(shí),可通過該方法進(jìn)行適當(dāng)?shù)膬?yōu)化。
在首次渲染期間或者調(diào)用了forceUpdate方法后,該方法不會(huì)被調(diào)用
8.componentWillUpdate
接收到新的props或者state后,進(jìn)行渲染之前調(diào)用,此時(shí)不允許更新props或state。
9.componentDidUpdate
完成渲染新的props或者state后調(diào)用,此時(shí)可以訪問到新的DOM元素。
10.componentWillUnmount
組件被移除之前被調(diào)用,可以用于做一些清理工作,在componentDidMount方法中添加的所有任務(wù)都需要在該方法中撤銷,比如創(chuàng)建的定時(shí)器或添加的事件監(jiān)聽器。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 實(shí)例化首次實(shí)例化getDefaultPropsgetInitialStatecomponentWillMountr...
    以德扶人閱讀 510評(píng)論 0 51
  • 在組件的整個(gè)生命周期中,隨著該組件的props或者state發(fā)生改變,其DOM表現(xiàn)也會(huì)有相應(yīng)的變化。一個(gè)組件就是一...
    張chuner閱讀 328評(píng)論 0 2
  • 組件生命周期 參考閱讀: component-lifecycle react組件生命周期過程說明 react 組件...
    lyzaijs閱讀 2,529評(píng)論 0 3
  • 下圖詳細(xì)列述了 React 組件在整個(gè)生命周期中所涉及的方法和行為: 生命周期詳解 組件在整個(gè) ReactJS 的...
    楊慧莉閱讀 735評(píng)論 0 0
  • component是通過自定義的幾個(gè)函數(shù)來控制組件在生命周期中的各個(gè)階段動(dòng)作(本處所寫的state同意指當(dāng)前組件內(nèi)...
    冰Q閱讀 445評(píng)論 0 0