天天看點

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.props

    this.state

    通路資料
  • 可以傳回

    null

    false

    或任何React元件
  • 隻能出現一個頂級元件(不能傳回數組)
  • 不能改變元件的狀态
  • 不能修改DOM的輸出

5.componentDidMount

真實的DOM被渲染出來後調用,在該方法中可通過

this.getDOMNode()

通路到真實的DOM元素。此時已可以使用其他類庫來操作這個DOM。

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

6.componentWillReceiveProps

元件接收到新的

props

時調用,并将其作為參數

nextProps

使用,此時可以更改元件

props

state

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

7.shouldComponentUpdate

元件是否應當渲染新的

props

state

,傳回

false

表示跳過後續的生命周期方法,通常不需要使用以避免出現bug。在出現應用的瓶頸時,可通過該方法進行适當的優化。

在首次渲染期間或者調用了

forceUpdate

方法後,該方法不會被調用

8.componentWillUpdate

接收到新的

props

或者

state

後,進行渲染之前調用,此時不允許更新

props

state

9.componentDidUpdate

完成渲染新的

props

或者

state

後調用,此時可以通路到新的DOM元素。

10.componentWillUnmount

元件被移除之前被調用,可以用于做一些清理工作,在

componentDidMount

方法中添加的所有任務都需要在該方法中撤銷,比如建立的定時器或添加的事件監聽器。