生命週期(lifecycle)

生命週期表

截圖 2021-10-13 上午9.26.14.png

物件內部初始化state

event handle綁定實例(instance)的地方

componentDidMount會在component被render到DOM之後執行,初始化資料及API請求時推薦使用,減少在componentDidMount初始化state值(避免使用setState會造成效能過度)

在初次被更新時呼叫(第一次render除外),可以在此處操作DOM此處也適合API請求

組建卸載時觸發,這兒不會再重新render所以不應該在這使用setState,適合清除(API, 或是在componentDidMount中的訂閱)

不常用的生命週期

在component被render前調用,getDerivedStateFromProps是一個靜態函數(static)無法操作state,用來檢查state決定是否更新

執行時會傳入當前props, state(通常用來比較props和state),執行後返回一個物件(state更新的值)或是null表示不更新

截圖 2021-10-14 上午11.22.03.png

建議使用pureComponent減少手動使用shouldComponentUpdate,在render前被調用決定是否更新,會傳入兩個更新(下一次的值)參數(nextProps, nexState),返回true或false決定是否更新。

shouldComponentUpdate(nextProps, nextState) {
  console.log('--shouldComponentUpdate--')
  console.log('當前的state',this.state)
  console.log('下次更新時的props', nextProps)
  console.log('下次更新時的state', nextState)
	// true要更新, false則不更新畫面
  return false
}