1. 程式人生 > >React元件生命週期過程說明

React元件生命週期過程說明

例項化

首次例項化

  • getDefaultProps
  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

例項化完成後的更新

  • getInitialState
  • componentWillMount
  • render
  • componentDidMount

存在期

元件已存在時的狀態改變

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

銷燬&清理期

  • componentWillUnmount

說明

生命週期共提供了10個不同的API。

1.getDefaultProps

作用於元件類,只調用一次,返回物件用於設定預設的props,對於引用值,會在例項中共享。

2.getInitialState

作用於元件的例項,在例項建立時呼叫一次,用於初始化每個例項的state,此時可以訪問this.props

3.componentWillMount

在完成首次渲染之前呼叫,此時仍可以修改元件的state。

4.render

必選的方法,建立虛擬DOM,該方法具有特殊的規則:

  • 只能通過this.propsthis.state訪問資料
  • 可以返回nullfalse或任何React元件
  • 只能出現一個頂級元件(不能返回陣列)
  • 不能改變元件的狀態
  • 不能修改DOM的輸出

5.componentDidMount

真實的DOM被渲染出來後呼叫,在該方法中可通過this.getDOMNode()訪問到真實的DOM元素。此時已可以使用其他類庫來操作這個DOM。

在服務端中,該方法不會被呼叫。

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方法中新增的所有任務都需要在該方法中撤銷,比如建立的定時器或新增的事件監聽器。