學習React時一定要搞懂React的生命週期,React生命週期函式有很多,可以參考熱心網友製作的圖表,有支援多國語言。
作者圖表中指的副作用泛指:繪製Canvas 或 fetch讀取資料 Ajax 或 animation等動作
虛線以上階段 (constructor, render) :不應該做繪製Canvas 或 fetch, Ajax 讀取資料等動作
常用的生命週期函式
constructor 建構函式
注意:
- 一定要呼叫 super(props)
- constructor 裡不要 setState()
- constructor 裡不要把 props 的屬性指定給 state
- constructor 裡不要 呼叫 Ajax fetch 等等資料
render 渲染函式
把資料轉成視覺畫面,或做資料的轉換
資料的轉換如:
const {count} = this.state
visulCount = count * 2
在 react 16後
render 函式裡,可以 return
- 一個 div (JSX元素)
- 一個 array
- 一個 string / 布林 / null / Portal
注意:
- render 裡不要 setState(),會陷入無窮迴圈
- render 裡不要讀取資料 EX: Ajax
componentDidMount
componentDidMount 時可以
- 讀取遠端資料 Ex: fetch
- 畫canvas
componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot) {xxxx}
- 一定要做 props & state 的 condition 條件比較
componentWillUnmount
常用在取消監聽事件,取消ajax,取消timeout事件
不常用的生命週期函式
getDerivedStateFromProps
從props的變動去取得新的state
static getDerivedStateFromProps(nextProp, prevState) { return 新的state 或 null }
注意:
- 是一種靜態的函式,函式裡不會有this可以用
- 在函式裡不用做 async 的操作
- 要回傳新的 state
- 在 component 掛載時/更新時,都會呼叫這個函式
shouldComponentUpdate
控制組件更新的時間,提昇效能
shouldComponentUpdate(nextProps, nexState) {
return true;
}