React學習筆記9---組件的生命周期

組件的聲明周期

理解

  • 組件從創(chuàng)建到死亡他會經(jīng)歷一些特定的階段
  • React組件中包含一系列的鉤子函數(shù)(聲明周期回調(diào)函數(shù)),會在特定的時刻調(diào)用
  • 我們在定義組件時,會在特定的聲明周期回調(diào)函數(shù)中,做特定的工作

聲明周期回調(diào)函數(shù)(舊)

  • 掛載時
掛載時
|
constructor
|
componentWillMount
|
render
|
componentDidMount
|
componentWillUnmount
  • setState
setState()
|
shouldComponentUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount
  • forceUpdate
forceUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount
  • 父組件render
父組件render
|
componentWillReceiveProps
|
shouldComponentUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount

生命周期的三個階段(舊)

  • 初始化階段:由ReactDom.render()觸發(fā),初次渲染
    1. constructor
    2. componentWillMount
    3. render
    4. componentDidMount
  • 更新階段:由組件內(nèi)部的this.setState()和父組件重新render觸發(fā)
    1. shouleComponentUpdate
    2. componentWillUpdate
    3. render
    4. componentDidUpdate
  • 卸載階段:由ReactDom.unmountComponentAtNode()觸發(fā)
    1. componentWillUnmount

生命周期流程圖(新)

  • 掛載時
掛載時
|
constructor
|
getDerivedStateFromProps
|
render
|
componentDidMount
  • 更新時
newProps
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
setState
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
(forceUpdate)
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
  • 卸載時
ReactDom.unmountComponentAtNode
|
componentWillUnmount

生命周期的三個階段(新)

  1. 初始化階段,由ReactDom.render()觸發(fā),初次渲染
  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount
  1. 更新階段,由組件內(nèi)this.setState()和父組件重新render觸發(fā)
  • getDerivedStateFromProps()
  • shodleComponentUpdate()
  • render()
  • getSnapShotBeforeUpdate()
  • componentDidUpdate
  1. 卸載階段,由ReactDom.unmountComponentAtNode()觸發(fā)
  • componentWillUnmount

重要的鉤子

  1. render():初始化渲染和更新渲染調(diào)用
  2. componentDidMount:掛載完成時調(diào)用,開啟監(jiān)聽,調(diào)用ajax請求
  3. componentWillUnmount:做一些收尾工作,比如清除定時器

即將廢棄的鉤子

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

現(xiàn)在使用會發(fā)出警告(16版本),下個大版本需要加上UNSAFE_前綴才能使用(17+),以后可能被徹底廢棄掉,不建議使用

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容