React16.3.0開始,生命週期進行了一些變化。本文主要介紹React16.3.0以後的生命週期。javascript
16版本以前的react組件的生命週期相信你們已經很熟悉。16版本的react對組件的生命週期函數進行了一些修改,下面進行詳細說明。java
建立期:
運行時:
props發生變化時react
state發生變化時git
卸載時
componentWillUnmount()github
建立期:
或者以下生命週期:segmentfault
注意: getDerivedStateFromProps/getSnapshotBeforeUpdate 和 componentWillMount/componentWillReceiveProps/componentWillUpdate 若是同時存在,React會在控制檯給出警告信息,且僅執行 getDerivedStateFromProps/getSnapshotBeforeUpdate 【React@16.7.0】網絡
運行時:
props發生變化時dom
或者以下生命週期:函數
state發生變化時性能
或者以下生命週期:
銷燬時
componentWillUnmount()
新的生命週期圖示:
constructor生命週期,如不須要,可缺省。一般會在 constructor 方法中初始化 state 和綁定事件處理程序。
可是,若是寫了constructor,那麼必須在其中調用super(props);不然可能會引發報錯。
如:
class Base extends Component { constructor(props) { super(); //應該爲 super(props); } state = { name: this.props.name } //....code }
拋出異常: Uncaught TypeError: Cannot read property 'name' of undefined.
一樣,若是定義了context,在state中須要使用this.context去獲取context上的內容,則須要super(props, context);
不過,若是你缺省constructor,那麼在state中,能夠放心的使用 this.props 或者是 this.context,不會引發報錯。
class Base extends Component { state = { name: this.props.name, color: this.context.color } //....code }
初始化的state一樣能夠在constructor中定義。若是須要給方法綁定this,那麼統一在constructor中進行。
當組件的state須要根據props來改變的時候可調用此方法。這個方法是在 render() 前會被執行,每次觸發render前,都會觸發此方法。
該方法有兩個參數props和state; 返回值爲state對象, 不須要返回總體state,把須要改變的state返回便可。若是不須要,能夠返回null.
class Base extends Component { state = { age: 20 } static getDerivedStateFromProps(props, state) { return { age: 50 } } render() { // 50 return ( <div>{this.state.age}</div> ) } }
這個方法容許組件基於 props 的變動來更新其內部狀態,以這種方式得到的組件狀態被稱爲派生狀態。應該謹慎使用派生狀態,可能會引入潛在的錯誤
React組件中必需要提供的方法。當state或者props任一數據有更新時都會執行。
render() 是一個純函數,所以,不要在其中執行setState諸如此類的操做。render必須有一個返回值,返回的數據類型能夠有:
注意不要在render中調用setState
componentDidMount()方法是在組件加載完後當即執行,也就是當該組件相關的dom節點插入到dom樹中時。該方法在組件生命中只執行一次。
通常狀況,咱們會在這裏setState(),或者進行接口請求,設置訂閱等。
class Base extends Component { state = { age: 20 } componentDidMount() { this.fetchDate(); } render() { return ( <div>{this.state.age}</div> ) } //other code }
在渲染新的props或state前,shouldComponentUpdate被調用,默認返回true。forceUpdate()時不會調用此方法。
若是shouldComponentUpdate()返回false,那麼getSnapshotBeforeUpdate,render和componentDidUpdate不會被調用。
今生命週期主要用於優化性能。
在render()的輸出被渲染到DOM以前被調用。使組件可以在它們被更改以前捕獲當前值(如滾動位置)。這個生命週期返回的任何值都將做爲第三個參數傳遞給componentDidUpdate().
在更新發生後調用 componentDidUpdate()。當組件更新時,將此做爲一個機會來操做DOM。如將當前的props與之前的props進行比較(例如,若是props沒有改變,則可能不須要網絡請求。
若是組件使用 getSnapshotBeforeUpdate(),則它返回的值將做爲第三個「快照」參數傳遞給 componentDidUpdate()。不然,這個參數是undefined。
在組件被卸載並銷燬以前當即被調用。在此方法中執行任何須要的清理,例如使定時器無效,取消網絡請求或清理在componentDidMount()中建立的任何監聽。
最後,說明一點:
componentWillUpdate,componentWillReceiveProps,componentWillUpdate這三個生命週期在React將來版本中會被廢棄。
而UNSAFE_componentWillUpdate,UNSAFE_componentWillReceiveProps,UNSAFE_componentWillUpdate 將來版本中仍可繼續使用。
初始化階段(父組件和子組件):
運行階段:父組件props/state更新
子組件的shouldComponentUpdate返回false,則子組件其後的生命週期都不在進行,可是父組件的生命週期繼續執行。
卸載階段: 卸載父組件
若是本博文給了您一點啓發或者是幫助,請給個人github點顆Star吧:https://github.com/YvetteLau/...
參考: