複習React生命週期

image.png

初始化掛載階段

  • ! getDefaultProps:獲取實例的默認屬性 (只支持 React.createClass 建立的組件)性能優化

  • ! getInitialState:獲取每一個實例的初始化狀態 (只支持 React.createClass 建立的組件)markdown

  • constructor 函數中不要調用 setState() 方法。若是你的組件須要使用內部 state,請直接在構造函數中爲 this.state 賦值初始 state網絡

    • 經過給 this.state 賦值對象來初始化內部 state
    • 爲事件處理函數綁定實例
    constructor(props) {
      super(props);
      // 不要在這裏調用 this.setState()
      this.state = { counter: 0 };
      this.handleClick = this.handleClick.bind(this);
    }
    複製代碼
  • ! componentWillMount:在組件掛載以前被調用。它在 render() 以前調用,所以在此方法中同步調用 setState() 不會觸發額外渲染,在新版本中使用建議使用 UNSAFE_componentWillMount 代替函數

  • render:組件在這裏根據元素的類型生成虛擬DOM節點性能

  • componentDidMount:會在組件掛載後(插入 DOM 樹中)當即調用。依賴於 DOM 節點的初始化應該放在這裏。如需經過網絡請求獲取數據,此處是實例化請求的好地方優化

運行中狀態: 當組件的props 或者state 更新以後

  • componentWillReceiveProps(nextProps): 會在已掛載的組件接收新的 props 以前被調用,若是你須要更新狀態以響應 props 更改(例如,重置它),你能夠比較 this.propsnextProps 並在此方法中使用 this.setState() 執行 state 轉換 UNSAFE_componentWillReceiveProps()ui

  • shouldComponentUpdate(): 組件接受到新屬性或者新狀態的時候(能夠返回 false,接收數據後不更新,阻止 render 調用,後面的函數不會被繼續執行了)此方法僅做爲性能優化的方式而存在。不要企圖依靠此方法來「阻止」渲染,由於這可能會產生 bug。,PureComponent 會對 props 和 state 進行淺層比較,並減小了跳過必要更新的可能性。this

  • ! componentWillUpdate(nextProps, nextState) : 當組件收到新的 props 或 state 時會在渲染以前調用此方法,使用此做爲在更新發生以前執行準備更新的機會。初始渲染不會調用此方法。不能此方法中調用 this.setState();在 componentWillUpdate() 返回以前,也不該該執行任何其餘操做(例如,dispatch Redux 的 action)觸發對 React 組件的更新,此方法以過期 UNSAFE_componentWillUpdate() spa

  • render:組件渲染組件code

  • getSnapshotBeforeUpdate(prevProps, prevState) , getSnapshotBeforeUpdate() 在最近一次渲染輸出(提交到 DOM 節點)以前調用。它使得組件能在發生更改以前從 DOM 中捕獲一些信息(例如,滾動位置)。今生命週期的任何返回值將做爲參數傳遞給 componentDidUpdate()

  • componentDidUpdate(prevProps, prevState, snapshot): 組件已經更新 會在更新後會被當即調用。首次渲染不會執行此方法。

銷燬階段:

  • componentWillUnmount:組件即將銷燬 會在組件卸載及銷燬以前直接調用。在此方法中執行必要的清理操做,例如,清除 timer,取消網絡請求或清除在 componentDidMount() 中建立的訂閱等。
相關文章
相關標籤/搜索