react生命週期執行順序測試

項目地址:github.com/wangxiaofei…react

測試

首次渲染

father constructor
father getDerivedStateFromProps
father render
children constructor
children getDerivedStateFromProps
children render
children componentDidMount
father componentDidMount
複製代碼

父組件數據修改觸發重渲染

father getDerivedStateFromProps
father shouldComponentUpdate
father render
children getDerivedStateFromProps
children shouldComponentUpdate
children render
children getSnapshotBeforeUpdate
father getSnapshotBeforeUpdate
children componentDidUpdate, snapshot: 1
father componentDidUpdate, snapshot: 1
複製代碼

父組件調用forceUpdate

father getDerivedStateFromProps
father render
children getDerivedStateFromProps
children shouldComponentUpdate
children render
children getSnapshotBeforeUpdate
father getSnapshotBeforeUpdate
children componentDidUpdate, snapshot: 1
father componentDidUpdate, snapshot: 1
複製代碼

銷燬

father componentWillUnmount
children componentWillUnmount
複製代碼

總結

舊生命週期在各個階段的調用狀況

  1. 掛載
    • constructor
    • componentWillMount
    • render
    • componentDidMount
  2. 更新
    • componentWillReceiveProps
    • shouldComponentUpdate
    • componentWillUpdate
    • render
    • componentDidUpdate
  3. 卸載
    • componentWillUnmount

新生命週期在各個階段的調用狀況

  1. 掛載
    • constructor
    • getDerivedStateFromProps
    • render
    • componentDidMount
  2. 更新
    • getDerivedStateFromProps
    • shouldComponentUpdate
    • render
    • getSnapshotBeforeUpdate
    • componentDidUpdate
  3. 卸載
    • componentWillUnmount

父子組件之間的生命週期函數的調用順序

  • 掛載階段,只有當執行到render的時候,父組件的constructor纔開始執行,知道子組件掛載完成(componentDidMount),父組件纔算掛載完成
  • 更新階段,相似掛載階段,只有父組件執行到render,纔開始子組件的getDerivedStateFromProps -> shouldComponentUpdate -> render,但再父組件的getSnapshotBeforeUpdate是緊隨在子組件的getSnapshotBeforeUpdate後,而後子組件在componentDidUpdate

父組件調用forceUpdate

組件調用forceUpdate方法後,不會執行shouldComponentUpdate,會執行getDerivedStateFromProps,而後再render,後面的生命週期和更新一致git

相關文章
相關標籤/搜索