最新 React 的生命周期

React 16.3 版本之前 生命周期
React 新版 生命周期

生命周期方法介紹

constructor(props)

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}

React組件的構造方法,函數中主要完成對state的初始化,以及綁定事件處理的方法。

static getDerivedStateFromProps(props, state)

該方法當屬性改變或者狀態改變時都會觸發,不建議使用異步處理獲取數據,應為一個純函數,返回值是一個state對象

componentWillMount()

在組件掛載之前調用且整個組件生命周期中只調用一次
該方法中可以執行setState,且不會觸發重新渲染。

該生命周期在React v16.3 廢棄,將在v17 之后徹底棄用,可以替換為 UNSAFE_componentWillMount(),當static getDerivedStateFromProps(),getSnapshotBeforeUpdate() 生命周期存在時,該方法將不起作用

render()

reander 是必須定義的一個生命周期,渲染dom,在該方法中不可直接執行setState。

componentDidMount()

在組件掛載之后調用且整個組件生命周期中只調用一次
該方法中可以發起異步請求,可以執行setState
該方法可以使用refs獲取真實dom元素,進行dom相關操作

componentWillReceiveProps(nextProps)

當組件props發生變化時或者父組件重新渲染時觸發
該方法中可通過參數nextProps獲取變化后的props,可通過this.props訪問變化之前的props。
該方法中可以執行setState

該生命周期在React v16.3 廢棄,將在v17 之后徹底棄用,可以替換為 UNSAFE_componentWillReceiveProps(),當static getDerivedStateFromProps(),getSnapshotBeforeUpdate() 生命周期存在時,該方法將不起作用

shouldComponentUpdate(nextProps, nextState)

當組件重新渲染時會觸發
該方法返回true或者false,當返回true進行重新渲染,當返回false時將阻止重新渲染
該方法可用來優化組件,通過判斷true or false, 減少組件的重復渲染

componentWillUpdate()

組件更新之前當shouldComponentUpdate方法返回true時調用
該方法中不可執行setState

該生命周期在React v16.3 廢棄,將在v17 之后徹底棄用,可以替換為 UNSAFE_componentWillUpdate(),當static getDerivedStateFromProps(),getSnapshotBeforeUpdate() 生命周期存在時,該方法將不起作用

getSnapshotBeforeUpdate(prevProps, prevState)

class ScrollingList extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (prevProps.list.length < this.props.list.length) {
      const list = this.listRef.current;
      return list.scrollHeight - list.scrollTop;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // If we have a snapshot value, we've just added new items.
    // Adjust scroll so these new items don't push the old ones out of view.
    // (snapshot here is the value returned from getSnapshotBeforeUpdate)
    if (snapshot !== null) {
      const list = this.listRef.current;
      list.scrollTop = list.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <div ref={this.listRef}>{/* ...contents... */}</div>
    );
  }
}

componentDidUpdate(prevProps, prevState, snapshot)

組件更新之后調用,和componentDidMount類似

componentWillUnmount()

組件將被銷毀時觸發
該方法中可以進行清理操作。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容