2020: Vue和React生命週期

Vue 生命週期

vue2有9個生命週期鉤子
vue3也有9個生命週期鉤子

2.x和3.x鉤子的對應關係:

beforeCreate -> 使用 setup()
created -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured

3.x新增鉤子:

onRenderTracked
onRenderTriggered

兩個鉤子函數都接收一個 DebuggerEvent,與 watchEffect 參數選項中的 onTrackonTrigger

React 生命週期

react16版本之前有7個生命週期鉤子
react16版本之後也有7個生命週期鉤子

16版本之前

  • componentWillMount (過時)
  • componentDidMount
  • componentWillReceiveProps (過時)
  • shouldComponentUpdate
  • componentWillUpdate (過時)
  • componentDidUpdate
  • componentWillUnmount

16版本之後

  • getDeriveStateFromProps (新增)
  • componentDidMount
  • shouldComponentUpdate
  • getSnapshotBeforeUpdate (新增)
  • componentDidUpdate
  • componentWillUnmount
  • componentDidCatch (新增)

React新增的生命週期函數說明

  1. getDerivedStateFromProps (nextProps, prevState)
    它配合 componentDidUpdate 週期函數,用來替代 componentWillReceiveProps。
    將原本 componentWillReceiveProps 功能進行劃分 —— 更新 state 和 操作/調用 props,很大程度避免了職責不清而導致過多的渲染, 從而影響應該性能。

  2. getSnapshotBeforeUpdate (prevProps, prevState)
    用來替代componentWillUpdate;
    在組件更新之前獲取一個 snapshot —— 可以將計算得的值或從 DOM 得到的信息傳遞到 componentDidUpdate(prevProps, prevState, snapshot) 週期函數的第三個參數,常常用於 scroll 位置的定位。

  3. componentDidCatch(error, info)
    讓開發者可以自主處理錯誤信息,諸如展示,上報錯誤等
    react lifecycle hooks

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章