1. 程式人生 > >React 較難理解的生命週期鉤子函式

React 較難理解的生命週期鉤子函式

1.   constructor

在react中,class 裡的constructor 方法 用來初始化state和繫結事件方法
其中,super作為方法執行父類的建構函式,引數為props 即接受父元件傳入的props

如果沒有執行super, react會報錯

  1. componentWillReceiveProps(nextProps)

執行時間:當一個已mount的react元件接收到新的props的時候會自動呼叫該鉤子
引數:nextProps

注意:
即使props沒有改變,該方法也可能會被呼叫,因此需要將新舊props值進行對比然後操作
在元件mounting階段,該方法不會被掉起,setState 也不會觸發該方法

// 更新子元件中的state,當查詢引數變化的時候  
componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.query) !== JSON.stringify(this.props.query)) {
      this.setState({
        hasmore: true,
        loading: false,
        count: 0,
        page: nextProps.page,
      }, () => {
        this.listener();
        this
.autoLoad(nextProps); }); }
  1. shouldComponentUpdate (nextProps,nextState)

執行時間:當的判斷state或者props 的變化 是否影響元件的output的時候
返回true 表示不影響,即元件正常執行render方法
返回false 表示影響, 即元件不執行render方法,但返回false不會阻止子元件在其狀態更改時重新呈現
注意:
返回false 會阻止 componentWillUpdate,render,componentDidUpdate 的呼叫,未來react可能會削弱這種強阻止的行為,該用提示的形式。

初始化render的時候或者執行forceUpdate的時候,不會執行該方法。

 shouldComponentUpdate(nextProps, nextState) {
    if (this.props.children === nextProps.children) { 
      return false;
    }
    return true;
  }
  1. componentWillUnmount()

執行時間:當component被unmounted 和destroyed 的時候

在這個鉤子函式內部 可以取消 componentDidMount方法中定義的 定時器,網路請求,以及DOM元素