react生命週期

實例化

首次實例化segmentfault

  • getDefaultProps
  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

實例化完成後的更新數組

  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

存在期

組件已存在時的狀態改變優化

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

銷燬&清理期

  • componentWillUnmount

說明

生命週期共提供了10個不一樣的API。this

1.getDefaultProps

做用於組件類,只調用一次,返回對象用於設置默認的props,對於引用值,會在實例中共享。code

2.getInitialState

做用於組件的實例,在實例建立時調用一次,用於初始化每一個實例的state,此時能夠訪問this.propscomponent

3.componentWillMount

在完成首次渲染以前調用,此時仍能夠修改組件的state。對象

4.render

必選的方法,建立虛擬DOM,該方法具備特殊的規則:生命週期

  • 只能經過this.propsthis.state訪問數據
  • 能夠返回nullfalse或任何React組件
  • 只能出現一個頂級組件(不能返回數組)
  • 不能改變組件的狀態
  • 不能修改DOM的輸出

5.componentDidMount

真實的DOM被渲染出來後調用,在該方法中可經過this.getDOMNode()訪問到真實的DOM元素。此時已可使用其餘類庫來操做這個DOM。事件

在服務端中,該方法不會被調用。get

6.componentWillReceiveProps

組件接收到新的props時調用,並將其做爲參數nextProps使用,此時能夠更改組件propsstate

componentWillReceiveProps: function(nextProps) {
        if (nextProps.bool) {
            this.setState({
                bool: true
            });
        }
    }

7.shouldComponentUpdate

組件是否應當渲染新的propsstate,返回false表示跳事後續的生命週期方法,一般不須要使用以免出現bug。在出現應用的瓶頸時,可經過該方法進行適當的優化。

在首次渲染期間或者調用了forceUpdate方法後,該方法不會被調用

8.componentWillUpdate

接收到新的props或者state後,進行渲染以前調用,此時不容許更新propsstate

9.componentDidUpdate

完成渲染新的props或者state後調用,此時能夠訪問到新的DOM元素。

10.componentWillUnmount

組件被移除以前被調用,能夠用於作一些清理工做,在componentDidMount方法中添加的全部任務都須要在該方法中撤銷,好比建立的定時器或添加的事件監聽器。

更加詳細的介紹:https://segmentfault.com/a/1190000004168886

相關文章
相關標籤/搜索