生命週期是一個組件從建立到銷燬的過程。react會在不一樣的時間點注入相應的鉤子函數,以便於開發者進行更靈活的數據處理。react
生命週期只存在於類組件中,函數組件沒有生命週期。可是在後來的新版本react提供了hooks用於管理函數組件的狀態。
constructor(props)
函數:ajax
setState
,頁面還未掛載。componentWillMount
函數:數組
setState
,可是很容易致使bug,不建議在這裏使用;render
函數:性能優化
setState
方法,會形成無限遞歸內存泄露。componentDidMount
函數:微信
componentWillReceiveProps(nextProps)
函數:dom
shouldComponentUpdate(nextProps, nextState)
函數:異步
true
執行render
函數,返回false
不執行render
函數;componentWillUpdate(nextProps, nextState)
函數:函數
componentDidUpdate(prevProps, prevState, snapshot)
函數:性能
componentWillUnmount()
函數:優化
官方圖解已經畫的很清楚了,這裏不在贅述,主要說一下區別。
componentWillMount
函數
componentWillReceiveProps
函數
componentWillUpdate
函數
getDerivedStateFromProps(props, state)
函數
static
關鍵字;getSnapshotBeforeUpdate(prevProps, prevState)
函數
componentDidUpdate(prevProps, prevState, snapshot)
連用,返回的值做爲該函數的第三個參數傳入。setSate
在dom事件處理函數中調用時就是異步的;舉個例子:
import React, {Component} from 'react' export default class index extends Component{ state = { count: 0 } //點擊一次count加2 hanldeClick = () => { this.State({ count: this.state.count + 1 }) this.State({ count: this.state.count + 1 }) } render(){ return ( <div onClick={this.hanldeClick}>{this.state.count}</div> ) } }
根據上述代碼,在點擊div
以後,按道理,count
的值應該變成2
,但實際顯示的確是1
。
解決辦法:給setState
傳入一個函數更新數據。
//點擊一次count加2 hanldeClick = () => { //使用這種方式獲取的上一個state是最新的 this.State(function(state, props) { return { count: state.count + 2 }; }) }
react團隊以爲,dom事件處理函數中狀態處理會比較複雜,setState
的次數比較多,若是每次setState
就去更新頁面,會影響頁面渲染效率,因此會將事件中的多個setState
合併成同一個。