react生命週期新舊對比
react生命週期16.0前的生命週期
首次進去頁面執行的生命週期鉤子函式有:(初始化階段和掛載階段)
1.constructor (初始化資料,也可以super(props) 呼叫基類的構造方法 props只讀不可變,state可變)
2.componentWillMount ( 在元件掛載到DOM前呼叫 )
3.render ( 不負責元件實際渲染工作,之後由React自身根據此元素去渲染出頁面DOM )
4.componentDidMount ( 元件掛載到DOM後呼叫,且只會被呼叫一次,一般會在這個鉤子函式中做一些初始化的事情,例如:開啟定時器,傳送網路請求,訂閱訊息 )
更新階段:(一般由元件的內部this.setState()或者父元件render觸發)
1.元件自身呼叫setState更新
1.shouldComponentUpdate(注意:如果使用強制更新this.forceUpdate(),不會觸發該生命週期)
( 當更新時無論資料是否變化都呼叫,優化:可以使用回撥引數(nextProps,nextState)更新之後的資料來比較是否需要更新,false就不render,true繼續更新)
//控制組件更新的“閥門” shouldComponentUpdate(nexrProps,nextStates){ if(nextStates.count == this.state.count) returnfalse console.log('Count---shouldComponentUpdate'); return true }
2.componentWillUpdate
· 此方法在呼叫render方法前執行,在這邊可執行一些元件更新發生前的工作,一般較少用。
3.render
4.componentDidUpdate( prevProps, prevState )
· 此方法在元件更新後被呼叫,可以操作元件更新的DOM,prevProps和prevState這兩個引數指的是元件更新 前
2.父元件重新render或者父元件傳的props的值變化
componentWillReceiveProps ( nextProps )
·nextProps 是父祖件傳入的新增值,可以根據傳入值更新子元件的狀態。
//這種方式十分適合父子元件的互動,通常是父元件需要通過某些狀態控制子元件渲染亦或銷燬... componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一個引數代表即將傳入的新的Props if (this.props.sharecard_show !== nextProps.sharecard_show){ //在這裡我們仍可以通過this.props來獲取舊的外部狀態 //通過新舊狀態的對比,來決定是否進行其他方法 if (nextProps.sharecard_show){ this.handleGetCard(); } } }
shouldComponentUpdate
render
componentDidUpdate
react16.0以後的生命週期
首次進入頁面初始化的生命週期 (去除了componentWillMount)
constructor
static getDerivedStateFromProps (nextProps,prevState) 用來代替( componentWillReceiveProps )
兩者的引數是不相同的,而getDerivedStateFromProps
是一個靜態函式,也就是這個函式不能通過this訪問到class的屬性,也並不推薦直接訪問屬性。而是應該通過引數提供的nextProps以及prevState來進行判斷,根據新傳入的props來對映到state。
//若state的值在任何時候都取決於props,那麼可以使用getDerivedStateFromProps static getDerivedStateFromProps(nextProps, prevState) { const {type} = nextProps; // 當傳入的type發生變化的時候,更新state if (type !== prevState.type) { return { type, }; } // 否則,對於state不進行任何操作 return null;//必寫否則報錯 }
render
componentDidMount
更新階段生命週期
getDerivedStateFromProps
shouldComponentUpdate(注意:如果使用強制更新this.forceUpdate(),不會觸發該生命週期)
render
getSnapshotBeforeUpdate
componentDidUpdate
總結:
1.React16新的生命週期棄用了componentWillMount、componentWillReceivePorps,componentWillUpdate
2.新增了getDerivedStateFromProps、getSnapshotBeforeUpdate來代替棄用的三個鉤子函式(componentWillMount、componentWillReceivePorps,componentWillUpdate)
react更新生命週期原因:https://www.zhihu.com/question/278328905