1. 程式人生 > 其它 >react: 生命週期

react: 生命週期

1. 舊版本的宣告週期

1. 原理解析

初始化階段: 由ReactDOM.render()觸發初次渲染

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount() =====> 常用

更新階段,由元件內部this.setSate()或父元件render觸發

  1. componentWillReceiveProps(),父元件第一次render不觸發,第二次及之後render()時才會觸發
  2. shouldComponentUpdate()
  3. componentWillUpdate()
  4. render() =====> 必須使用的一個
  5. componentDidUpdate()
  6. 若執行shouldComponentUpdate方法返回true時可以正常繼續下面的流程
  7. 若shouldComponentUpdate方法返回false時則返回,不執行後面的流程
  8. 強制更新時會跳過shouldComponentUpdate()

解除安裝階段,由ReactDOM.unmountComponentAtNode()觸發

  1. componentWillUnmount() =====> 常用

2. 原理圖

2. 新版本宣告週期

刪除了componentWillMount(),componentWillReceiveProps(), componentWillUpdate()

1. getDerivedStateFromProps

  • 必須用static修飾
  • 若state的值在任何時候都取決於props,那麼可以使用getDerivedStateFromProps
  • 接收兩個引數,props和state
  • 若返回值不為null,則將返回值和state進行合併

2. getSnapshotBeforeUpdate

  • 該方法的返回值作為引數傳遞給componentDidUpdate,即下面的snapshotValue
  • componentDidUpdate(preProps,preState,snapshotValue)

3. 原理解析

初始化階段: 由ReactDOM.render()觸發初次渲染

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount() =====> 常用

更新階段,由元件內部this.setSate()或父元件render觸發

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render() =====> 必須使用的一個
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()
  6. 若執行shouldComponentUpdate方法返回true時可以正常繼續下面的流程
  7. 若shouldComponentUpdate方法返回false時則返回,不執行後面的流程
  8. 強制更新時會跳過shouldComponentUpdate()

解除安裝階段,由ReactDOM.unmountComponentAtNode()觸發

  1. componentWillUnmount() =====> 常用

2. 原理圖

如果文章對您有所幫助,可以點一下推薦哦