React 生命週期鉤子

圖片描述

3個階段

image

掛載階段

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount

1. constructor

class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {}
}

ES6 class構造方法,接收一個props屬性對象,props由父組件傳入,若是父組件未傳入,則指向自身。後端

一般用於初始化state,以及綁定事件處理方法等工做優化

2.componentWillMount

組件被掛載到DOM前,只會調用1次, 通常用用更靠前的constructor代替,在其中調用this.setState()不會引發組件從新渲染。this

3. render

組件的惟一必要方法,根據組件的propsstate返回一個React元素,用於描述組件的UI
imagespa

4.componentWillMount

組件被掛載到DOM後調用,且只會被掉用一次。在其中調用this.setState()會引發組件從新渲染,組件本次的更新尚未執行完成,又會進入新一輪的更新,致使不斷循環更新,進入死循環。
反作用操做,一般用於向後端請求數據。code

更新階段

  1. componentWillReceiveProps(nextProps)
  2. shoudComponentUpdate(nextProps, nextSate)
  3. componentWillUpdate
  4. render
  5. componentDidUpadate(prevProps, prevState)

1.componentWillReceiveProps(nextProps)

props變化會觸發componentWillReceiveProps,setState()不會觸發
imagecomponent

2.shoudComponentUpdate(nextProps, nextSate)

判斷組件是否繼續更新,減小沒必要要渲染,優化
image對象

3.componentWillUpdate

在render前調用,做爲組件更新前執行某些工做過的地方,(shoudComponentUpdate, componentWillUpdate 不能調用setState()避免引發循環調用)事件

4.componentDidUpadate(prevProps, prevState)

組件更新後調用,能夠做爲更新後調用DOM的地方,兩個參數表明prevProps, prevState,
更新前的屬性和狀態。圖片

卸載階段

組件從DOM中移除的階段。可用於清楚組件中使用中的定時器,清除componentDidMount手動建立的DOM等等,避免內存泄露。內存

相關文章
相關標籤/搜索