React生命周期總結


react生命周期流程

1.初始化,首次render

  • getDefaultProps()

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

  • getInitialState()

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

  • componentWillMount()

    componentWillMount只在初始化時候被調用一次,可以使用setState方法,會立即更新state,然后接着進行render。

  • render()

    注意在render中千萬不可使用setState方法,不然馬上會引起無限的報錯了哈哈。如果其中包含其他的子組件,那么子組件的生命周期才開始進行。

  • componentDidmount()

    在子組件也都加載完畢后執行,在RN中就是指組件初始化加載完畢,在react中DOM渲染完成,此時就可以操作DOM了。

2.props發生改變時候更新

  • componentWillReceiveProps(nextProps)

    componentWillReceiveProps方法可以比較this.props和nextProps來看是否發生了變化,然后可以進行setState等操作。

    注意只要父組件此方法觸發,那么子組件也會觸發,也就是說父組件更新,子組件也會跟着更新。

  • 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請求


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM