React 重溫之 組件生命週期

生命週期

任何事物都不會憑空產生,也不會無端消亡。一個事物從產生到消亡經理的各個階段,咱們稱之爲 生命週期。html

具體到咱們的前端組件上來,一個組件的生命週期能夠大致分爲建立、更新、銷燬這個三個階段。前端

本文主要介紹React 的組件生命週期,並以最新發布的v16爲分水嶺,介紹先後生命週期函數的變化。react

組件生命週期

在React代碼裏,咱們一般經過繼承React.Component這個抽象基礎類來定義一個有生命週期函數的組件(函數式生命沒法自定義生命週期函數),react官方將其生命週期分爲如下三個階段:segmentfault

裝載

這個階段是指組件初始化並插入DOM中,主要包含如下函數:函數

constructor()
static getDerivedStateFromProps()
componentWillMount() / UNSAFE_componentWillMount()
render()
componentDidMount()

更新

當組件狀態發生變化時,會觸發一次更新spa

componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
static getDerivedStateFromProps()
shouldComponentUpdate()
componentWillUpdate() / UNSAFE_componentWillUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

銷燬

當組件從DOM中移除時,啓動銷燬:code

componentWillUnmount()

具體以下圖:component

React 生命週期函數

如上圖所示,綠色背景爲v16版本新增的生命週期函數,黃色背景的的爲v16版本建議棄用,並在後續版本中會刪除的生命週期函數。htm

其中getDerivedStateFromProps是一個靜態函數,用來替換原來的componentWillMount函數,能夠在這個靜態函數中將props裏的屬性添加到state中去,這裏應該是一個純函數。blog

getSnapshotBeforeUpdate用來作一些必需要修改真實DOM的操做,雖然不建議這麼作。

One more thing

React 同時提供一個componentDidCatch函數,來代表當前組件是一個邊界錯誤處理組件,具體能夠參考錯誤邊界

參考連接

相關文章
相關標籤/搜索