react生命週期詳解

react組件的生命週期的三個階段

建立階段、更新階段、銷燬階段。建立階段指react組件對應的虛擬dom被建立,react對應的真實的dom結構被建立,並被插入到dom中;更新階段是由props、state變化或者強制調用forceUpdate引發的dom更新,包括虛擬dom更新,實際dom結構更新;銷燬階段是指該組件的銷燬,從dom中移除。
react爲這三種階段的不一樣時機提供了不少鉤子,讓咱們執行對應的操做。下面將詳細地介紹一下這些鉤子函數。react

建立階段
1.constructor
2.componentWillMount
3.render
4.componentDidMount
更新階段
1.componentWillReceiveProps
2.shouldComponentUpdate
3.componentWillUpdate
4.render
5.componentDidUpdate
銷燬階段
1.componentWillUnmount
錯誤發生時
1.componentDidCatch(16新添加)

注意:調用setState方法引發的更新階段,不會調用componentWillReceiveProps方法,forceUpdate方法引發的更新不會調用componentWillReceiveProps和shouldComponentUpdate方法。瀏覽器

constructor(props)

注意若是存在,要調用super(props),適合初始化state和在this上掛載方法,不要在這裏註冊事件監聽,保證函數沒有反作用,在這裏面初始化state不用調setState方法,直接給state賦值。this.state={}網絡

render

能夠返回React elements、string、number、null、Portals,注意不能返回undefined。Portals是16添加的,app

ReactDOM.createPortal(ele, document.getElementById('app')

render方法應該保持pure,不能修改組件狀態。dom

componentWillMount

在componentWillMount後立馬觸發render,在這個裏面調用setState不會觸發新的渲染,不要在函數裏面引入反作用和事件訂閱函數函數

componentDidMount

獲取數據和訂閱事件都適合在這裏面。這個函數裏面的setState會觸發新的渲染,可是在瀏覽器更新屏幕以前發生,也就是說就算render方法在這種狀況下調用了兩次,用戶也不會看見兩次不同的頁面this

componentWillReceiveProps(nextProps)

能夠調用setState方法code

shouldComponentUpdate(nextProps, nextState)

默認時返回true,可使組件繼承React.PureComponent,這樣在這個方法調用時會對prop和state進行一個淺比較component

componentWillUpdate

不能調用setState也不要觸發一個會致使更新的操做繼承

componentDidUpdate

適合請求網絡獲取數據

componentWillUnmount

適合作必要的清除操做,好比使定時器失效,取消網絡請求,清除訂閱操做

相關文章
相關標籤/搜索