組件的聲明周期
理解
- 組件從創(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ā),初次渲染
- constructor
- componentWillMount
- render
- componentDidMount
- 更新階段:由組件內(nèi)部的this.setState()和父組件重新render觸發(fā)
- shouleComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
- 卸載階段:由ReactDom.unmountComponentAtNode()觸發(fā)
- componentWillUnmount
生命周期流程圖(新)
- 掛載時
掛載時
|
constructor
|
getDerivedStateFromProps
|
render
|
componentDidMount
- 更新時
newProps
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
setState
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
(forceUpdate)
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
- 卸載時
ReactDom.unmountComponentAtNode
|
componentWillUnmount
生命周期的三個階段(新)
- 初始化階段,由ReactDom.render()觸發(fā),初次渲染
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount
- 更新階段,由組件內(nèi)this.setState()和父組件重新render觸發(fā)
- getDerivedStateFromProps()
- shodleComponentUpdate()
- render()
- getSnapShotBeforeUpdate()
- componentDidUpdate
- 卸載階段,由ReactDom.unmountComponentAtNode()觸發(fā)
- componentWillUnmount
重要的鉤子
- render():初始化渲染和更新渲染調(diào)用
- componentDidMount:掛載完成時調(diào)用,開啟監(jiān)聽,調(diào)用ajax請求
- componentWillUnmount:做一些收尾工作,比如清除定時器
即將廢棄的鉤子
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
現(xiàn)在使用會發(fā)出警告(16版本),下個大版本需要加上UNSAFE_前綴才能使用(17+),以后可能被徹底廢棄掉,不建議使用