附實例!圖解React的生命周期及執行順序


本文由雲+社區發表

作者:前端林子

1.七個可選的生命周期

可以結合下圖來看:

img

(1) componentWillMount() 僅在render()方法前被調用一次,如果在該方法中調用了setState方法去改變組件的狀態值,那么調用render()后,將會直接看到改變過了的狀態值,並且不論狀態值怎么改變,componentWillMount()都不會再被調用。

(2) componentDidMount() 僅在render()方法后被立即調用一次(客戶端),相對於父組件而言,該方法在子組件中會先被調用。如果需要使用一些JaveScript框架或者類似於setInterval()這樣的方法,建議在該方法內使用。

(3) ShouldComponentUpdate(object nextProps, object nextState) 在初始渲染調用render()方法時不會被調用,后面在接受到新的state或者props時,在render()方法前被調用。為防止一些潛在的bug,該方法默認總是返回true。如果你確定state及props改變后不需要渲染組件,那么也可以指定返回false,需要注意的是,這樣的結果會導致后面的render()、componentWillUpdate()、componentDidUpdate()都不會被調用。

一般的,我們可以通過該函數來優化性能:

一個React項目需要更新一個小組件時,很可能需要父組件更新自己的狀態。而一個父組件的重新更新會造成它旗下所有的子組件重新執行render()方法,形成新的虛擬DOM,再用diff算法對新舊虛擬DOM進行結構和屬性的比較,決定組件是否需要重新渲染

無疑這樣的操作會造成很多的性能浪費,所以我們開發者可以根據項目的業務邏輯,在shouldComponentUpdate()中加入條件判斷,從而優化性能

例如React中的就提供了一個PureComponent的類,當我們的組件繼承於它時,組件更新時就會默認先比較新舊屬性和狀態,從而決定組件是否更新。值得注意的是,PureComponent進行的是淺比較,所以組件狀態或屬性改變時,都需要返回一個新的對象或數組

(4) componentWillReceiveProps(object nextProps) 在初始渲染調用render()方法時不會被調用,當接收到一個新的props時,該方法被調用。我們都知道,如果改變一個狀態的值,則會觸發render()方法,所以可以在這個方法里調用setState()方法去改變一個狀態的值,當該方法接收到新的props時,setState()就可以避免一次額外的render()了。 在這個方法里,尤其需要注意一點,就是接收到新的props一定會觸發render()方法,但是render()方法被觸發不一定是因為接收到了新的props

(5) componentWillUpdate(object nextProps, object nextState) 在初始渲染調用render()方法時不會被調用,當接收到新的props及state時,在render()方法之前被調用。

不要在此方法再去更新props 或者 state

(6) componentDidUpdate(object prevProps, object prevState) 在初始渲染調用render()方法時不會被調用,當組件更新被刷新到DOM之后被立即調用。

可以在這里訪問,並修改 DOM

(7) componentWillUnmount() 在組件從DOM上卸載前被調用,在這個方法里面,我們主要是完成一些清除操作,比如說清除掉一些過時了的定時器等。

2.執行順序及次數

(1) getDefaultProps(),調用1次

(2) getInitialState(),調用1次

(3) componentWillMount(),調用1次

(4) render(),調用>=1次

(5) componentDidMount():僅客戶端,調用1次

(6) componentWillReceiveProps(object nextProps),調用>=0次

(7) ShouldComponentUpdate(object nextProps, object nextState),調用>=0次

(8) componentWillUpdate(object nextProps, object nextState),調用>=0次

(9) render(),調用>=1次

(10) componentDidUpdate(object prevProps, object prevState),調用>=0次

(11) componentWillUnmount(),調用1次

3.實例

我寫了一個小demo可直接在瀏覽器里運行,大家可以通過控制台查看父組件、子組件中的各生命周期調用的順序:

<!DOCTYPE html>

<html>

    <head>

        <script src="https://fb.me/react-15.2.0.js"></script>

        <script src="https://fb.me/react-dom-15.2.0.js"></script>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

    </head>

<body>

    <div id="app-container"></div>

    <script type="text/babel">
        var SubCounter = React.createClass({
            componentWillReceiveProps:function() {
                console.log('9、子組件將要接收到新屬性');
            },

            shouldComponentUpdate:function(newProps, newState) {
                console.log('10、子組件是否需要更新');
                if (newProps.number < 5) return true;
                return false
            },

            componentWillUpdate:function() {
                console.log('11、子組件將要更新');
            },

            componentDidUpdate:function() {
                console.log('13、子組件更新完成');
            },

            componentWillUnmount:function() {
                console.log('14、子組件將卸載');
            },

            render:function() {
                console.log('12、子組件掛載中');
                return (
                        <p>{this.props.number}</p>
                )
            }
        });

        var Counter = React.createClass({
           
            getInitialState:function(){
                return(
                    this.state={
                        number:0
                    }
                )
            },

            componentWillMount:function(){
                console.log('3、父組件掛載之前');
            },

            componentDidMount:function(){
                console.log('5、父組件掛載完成');
            },

            shouldComponentUpdate:function(newProps, newState) {
                console.log('6、父組件是否需要更新');
                if (newState.number<15) return true;
                return false
            },

            componentWillUpdate:function() {
                console.log('7、父組件將要更新');
            },

            componentDidUpdate:function() {
                console.log('8、父組件更新完成');
            },

            handleClick : function(){
                this.setState({
                    number: this.state.number + 1
                })
            },
            render:function() {
                console.log('4、render(父組件掛載)');
                return (
                    <div>
                        <p>{this.state.number}</p>
                        <button onClick={this.handleClick}>+</button>
                        {this.state.number<10?<SubCounter number={this.state.number}/>:null}
                    </div>
                )
            }
        });        

        ReactDOM.render(<Counter />, document.getElementById('app-container'));

    </script>

</body>

</html>

點擊一次按鈕,通過控制台可以看到:

img

4.小結

本文主要是圖文結合地介紹了react的生命周期及執行順序,同時附上了一個實例,可以清楚地看到父組件、子組件的調用順序。如存在問題,歡迎指正~~~

此文已由騰訊雲+社區在各渠道發布

獲取更多新鮮技術干貨,可以關注我們騰訊雲技術社區-雲加社區官方號及知乎機構號


免責聲明!

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



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