React - 生命週期
React - 生命週期

前言
什麼是生命週期?就如同人有生老病死,React 組件也有類似的概念!
生命週期流程圖
初始化階段
由ReactDOM.render()觸發,按順序初次渲染
- constructor()- 初始化
 
- getDerivedStateFromProps- 需使用靜態方法 static
- 可以接收參數props,state
- 需返回一個狀態對象 或 null
 
- render()- 渲染
 
- componentDidMount()- DOM 掛載完成
 
更新階段
由組件內部this.setState()或父組件,重新render渲染
- getDerivedStateFromProps- 需使用靜態方法 static
- 可以接收參數props,state
- 需返回一個狀態對象 或 null
 
- shouldComponentUpdate()- 判斷是否繼續更新
 
- render()- 渲染
 
- getSnapshotBeforeUpdate- 更新前執行
- 需返回一個值 或 null
- 返回的快照值會給componentDidUpdate()
 
- componentDidUpdate()- 更新完成
- 有三個參數prevProps,prevState,snapshotValue
 
移除階段
由ReactDOM.unmountComponentAtNode()觸發
- componentWillUnmount()- 即將卸載
 
常用的三個生命週期
- render()- 初始化渲染
- 更新渲染
 
- componentDidMount()- 開啟監聽
- 發送 Ajax 請求
 
- componentWillUnmount()- 做一些收尾的工作,如:清空定時器
 
