react: 生命週期
阿新 • • 發佈:2021-12-02
1. 舊版本的宣告週期
1. 原理解析
初始化階段: 由ReactDOM.render()觸發初次渲染
- constructor()
- componentWillMount()
- render()
- componentDidMount() =====> 常用
更新階段,由元件內部this.setSate()或父元件render觸發
- componentWillReceiveProps(),父元件第一次render不觸發,第二次及之後render()時才會觸發
- shouldComponentUpdate()
- componentWillUpdate()
- render() =====> 必須使用的一個
- componentDidUpdate()
- 若執行shouldComponentUpdate方法返回true時可以正常繼續下面的流程
- 若shouldComponentUpdate方法返回false時則返回,不執行後面的流程
- 強制更新時會跳過shouldComponentUpdate()
解除安裝階段,由ReactDOM.unmountComponentAtNode()觸發
- 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()觸發初次渲染
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount() =====> 常用
更新階段,由元件內部this.setSate()或父元件render觸發
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render() =====> 必須使用的一個
- getSnapshotBeforeUpdate()
- componentDidUpdate()
- 若執行shouldComponentUpdate方法返回true時可以正常繼續下面的流程
- 若shouldComponentUpdate方法返回false時則返回,不執行後面的流程
- 強制更新時會跳過shouldComponentUpdate()
解除安裝階段,由ReactDOM.unmountComponentAtNode()觸發
- componentWillUnmount() =====> 常用