前言:因為生命周期是必須要掌握的,所以React的第二篇咱就寫這。
(版本:16.3.2)
React的生命周期大致分為四個狀態:分別是Mouting、Updating、Unmounting、Error handing。以下,讓我們來介紹各個狀態吧。
(注:不被官網推薦使用的我不會放入實際運行步驟中)
Mouting
創建實例插入Dom的過程狀態,將按以下順序調用這些方法:
- constructor()
- static getDerivedStateFromProps() (組建實例化時或props變化會被調用)
- componentWillMount() / UNSAFE_componentWillMount()
- render()
- componentDidMount()
constructor(): 需要初始化state值或bind函數時調用。該方法在類被加載前運行,在用該類時,需要調用super(props),不然props的調用會出錯。
static getDerivedStateFromProps(nextprops, prevstate):props變化時被調用,若是父組件重新渲染,也會被調用。它返回新的props值。
componentWillMount():render()前調用的一個函數,現官網不推薦使用。
render():組件的必需品。內容應為相對純粹的html文,返回null或false時,ReactDOM.findDOMNode(this)將返回null。
componentDidMount():組件裝填完畢后,立即被調用。通常DOM節點的初始化都在此,在此方法內調用setState()會調用兩次render(),需注意性能。
即若有設置state或bind函數時,整體必會調用的過程為
contructor() -> static getDerivedStateFromProps() -> render() -> componentDidMount()
Updating
通常在props或state值變化時被調用,將按以下順序調用方法:
- componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()
- static getDerivedStateFromProps() (組建實例化時或props變化會被調用)
- shouldComponentUpdate()
- componentWillUpdate() / UNSAFE_componentWillUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
componentWillReceiveProps():props變化時被調用,若是父組件重新渲染,也會被調用。setState通常不會調用該方法。現不被推薦使用。
static getDerivedStateFromProps(nextprops,prevstate):props變化時被調用,若是父組件重新渲染,也會被調用。它返回新的props值。
shouldComponentUpdate(nextProps, nextState):在props變化或執行setState時就會被調用,通常情況返回true。若返回false,componentWillUpdate()、render()、componentDidUpdate()將不會被調用。可通過this.props與nextProps或this.state與nextState比較,判斷是否返回true,不建議進行深度檢查或使用JSON.stringify(),效率會很低。另外以后可能會視為提示而不是嚴格指令。
componentWillUpdate(nextProps, nextState):渲染之前的一步操作,不能在這調用setState,現不被推薦使用。
render():組件的必需品。內容應為相對純粹的html文,返回null或false時,ReactDOM.findDOMNode(this)將返回null。
getSnapshotBeforeUpdate(prevProps, prevState):在最近的更改被提交到DOM元素前,使得組件可以在更改之前獲得當前值,此生命周期返回的任意值都會傳給componentDidUpdate()。
componentDidUpdate(prevProps, prevState, snapshot):更新完成后會立即調用此方法,snapshot的值即為getSnapshotBeforeUpdate的返回值。更新DOM節點的操作可放在這里進行。
即若只有state值變化時,整體必會調用的過程為
shouldComponentUpdate() -> render() -> getSnapshotBeforeUpdate() -> componentDidUpdate()
即若有prop值變化時,整體必會調用的過程為
static getDerivedStateFromProps() -> shouldComponentUpdate() -> render() -> getSnapshotBeforeUpdate() -> componentDidUpdate()
Unmounting
移除DOM節點時,會調用以下方法:
-
componentWillUnmount()
componentWillUnmount():組件銷毀之前會被調用。在此需要進行必要的清理,例如使定時器失效等。不能在此調用setState,因為到了這組件永遠不能再被渲染。
Error handing
渲染期間,在組件的生命周期內或是構造函數內發生error的話,將調用以下方法:
-
componentDidCatch()
componentDidCatch(error, info):錯誤邊界會抓取組件內JS的錯誤,並記錄顯示回退UI。它會捕獲渲染期間,生命周期方法以及下面整個樹的構造函數的錯誤。