React生命週期總結

react生命週期流程

1.初始化,首次render

  • getDefaultProps()react

    getDefaultProps 方法能夠用來設置組件屬性的默認值,在組件被創建時候就當即調用,全部實例均可以共享這些屬性。此時並不可使用this.state和setState。
    注意es6語法中就不這樣用了,在前面一篇文章中介紹過了區別。es6

  • getInitialState()ajax

    getInitialState 方法用於定義初始狀態,也不可使用this.state和setState。redux

  • componentWillMount()segmentfault

    componentWillMount只在初始化時候被調用一次,可使用setState方法,會當即更新state,而後接着進行render。
  • render()post

    注意在render中千萬不可以使用setState方法,否則立刻會引發無限的報錯了哈哈。若是其中包含其餘的子組件,那麼子組件的生命週期纔開始進行。
  • componentDidmount()this

    在子組件也都加載完畢後執行,在RN中就是指組件初始化加載完畢,在react中DOM渲染完成,此時就能夠操做DOM了。component

2.props發生改變時候更新

  • componentWillReceiveProps(nextProps)生命週期

    componentWillReceiveProps方法能夠比較this.props和nextProps來看是否發生了變化,而後能夠進行setState等操做。get

    注意只要父組件此方法觸發,那麼子組件也會觸發,也就是說父組件更新,子組件也會跟着更新。
  • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在接收了新的props或state後觸發,你能夠經過返回true或false來控制後面的生命週期流程是否觸發。

  • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在props或state改變或shouldComponentUpdate返回true後觸發。不可在其中使用setState。
  • render()

    從新渲染。
  • componentDidupdate(prevProps, prevState)

    會等子組件也都更新完後才觸發。

3.state發生改變時候更新

  • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在setState後state發生改變後觸發,你能夠經過返回true或false來控制後面的生命週期流程是否觸發。

  • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在state改變或shouldComponentUpdate返回true後觸發。不可在其中使用setState。
  • render()

    從新渲染。
  • componentDidupdate(prevProps, prevState)

    會等子組件也都更新完後才觸發。

3.組件銷燬

  • componentWillUnmount()

    組件銷燬時候觸發。

使用redux時候狀況

在使用redux作狀態管理時候,基本不須要透過生命週期去作setState這樣的狀態管理了,基本都是用props來傳遞來從新渲染,須要注意的僅僅是在哪一個生命週期時候觸發action,好比須要進行ajax請求時候通常都是在componentDidMount和componentWillReceiveProps時候進行,在reducer中處理完,而後在經過props傳入組件執行組件的更新週期。

參考資料

1.react生命週期

2.掘金

3.ajax請求

相關文章
相關標籤/搜索