React Class Component 至 Function Component with Hook API 的生命週期寫法的轉換整理
主要整理 React 16.3 以後的 Lifecycle ,因此將被棄用的就不再討論了。而官方也推薦使用 Hook API 來作為開發新的頁面使用,但不建議去重寫原來的 Class Component,新的 Hook API 可能會使你原本對 React 的認知一整個翻新,但對於 React 未來的 Roadmap 而言,學習 Hook API 是勢在必行。
React Class Component 從創建出來到被卸載會經歷的生命週期大概如下
- constructor
- render
- ComponentDidMount
- getDerivedStateFromProps
- shouldComponentUpdate
- getSnapshotBeforeUpdate
- componentDidUpdate
- componentWillUnmount
其他
- componentDidCatch
- forceUpdate
由於 Function Component 目前沒有辦法實現 getSnapshotBeforeUpdate 與 componentDidCatch 因此不在此描述,而 constructor 與 render 基本上不需要說明轉換了,Function Component 基本上本身就是 constructor 加 render。