React 生命周期可以分為三部分
一、掛載時
當組件實例被創建并插入 DOM 中時,其生命周期調用順序如下:
constructor()
-
static getDerivedStateFromProps()
(不常用) render()
componentDidMount()
二、更新時
-
static getDerivedStateFromProps()
(不常用) -
shouldComponentUpdate()
(不常用) render()
-
getSnapshotBeforeUpdate()
(不常用) componentDidUpdate()
三、卸載時
componentWillUnmount()
下面是生命周期的簡介
constructor()
在
React
組件掛載之前,會調用它的構造函數。
如果不初始化state
或不進行方法綁定,則不需要為React
組件實現構造函數。
注意??
在為React.Component
子類實現構造函數時,應在其他語句之前前調用super(props)
。否則,this.props
在構造函數中可能會出現未定義的bug
getDerivedStateFromProps(props, state)
getDerivedStateFromProps
會在調用render
方法之前調用。
并且在初始掛載及后續更新時都會被調用。它應返回
一個對象來更新state
,如果返回null
則不更新
任何內容。
render()
render()
方法是class
組件中唯一必須實現的方法
render()
函數應該為純函數,這意味著在不修改組件state
的情況下,每次調用時都返回相同的結果,并且它不會直接與瀏覽器交互
注意??
如需與瀏覽器進行交互,請在componentDidMount()
或其他生命周期方法中執行你的操作。保持render()
為純函數,可以使組件更容易思考
componentDidMount()
componentDidMount()
會在組件掛載后(插入 DOM 樹中)立即調用。
此時Virtual DOM
渲染完成。
此方法只會初始化一次,依賴于 DOM 節點的初始化應該放在這里。如需通過網絡請求獲取數據,此處是實例化請求的好地方。
這個方法是比較適合添加訂閱的地方。如果添加了訂閱,請不要忘記在componentWillUnmount()
里取消訂閱。
shouldComponentUpdate(nextProps, nextState)
此方法僅作為性能優化的方式而存在。
根據shouldComponentUpdate()
的返回值
(true
: 執行render()
,false
:不重新渲染
),判斷React
組件的輸出是否受當前state
或props
更改的影響。默認行為是state
每次發生變化組件都會重新渲染。大部分情況下,你應該遵循默認行為。
不要企圖依靠此方法來“阻止”渲染,因為這可能會產生bug
。你應該考慮使用內置的PureComponent
組件,而不是手動編寫shouldComponentUpdate()
注意??
后續版本,React 可能會將shouldComponentUpdate
視為提示而不是嚴格的指令,并且,當返回false
時,仍可能導致組件重新渲染。
getSnapshotBeforeUpdate(prevProps, prevState)
getSnapshotBeforeUpdate()
在最近一次渲染輸出(提交到 DOM 節點)之前調用。
它使得組件能在發生更改之前從 DOM 中捕獲一些信息(例如,滾動位置)。
此生命周期的任何返回值將作為參數傳遞給componentDidUpdate()
。
此用法并不常見,但它可能出現在 UI 處理中,如需要以特殊方式處理滾動位置的聊天線程等。
應返回snapshot
的值(或null
),返回值會在componentDidUpdate(prevProps, prevState, snapshot)
中的第三個參數
。
componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate()
會在更新后會被立即調用。
首次渲染不會執行此方法。
當組件更新后,可以在此處對 DOM 進行操作。
componentWillUnmount()
componentWillUnmount()
會在組件卸載及銷毀之前直接調用。在此方法中執行必要的清理操作,例如,清除timer
,取消網絡請求或清除在componentDidMount()
中創建的訂閱等。