React-^16.4 componentWillMount、componentWillReceivePorps替代方案

首先生命週期函數調用順序以下

  • constructor
  • getDerivedStateFromProps
  • ~~componentWillMount/UNSAVE_componentWillMount~~
  • render
  • componentDidMount(第一次render以後執行)

當組件的 propsstate 發生變化時會觸發更新。組件更新的生命週期調用順序以下:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

卸載 當組件從 DOM中移除時會調用以下方法:

  • componentWillUnmount()

有哪些⽣命週期被捨棄(3個),哪些⽣命週期是新增(2個)?

  • 捨棄
    • ~~componentWillMount~~
    • ~~componentWillReceivePorps~~
    • ~~componentWillUpdate~~
  • 新增
    • getDerivedStateFromProps (能夠用來替換componentWillReceiveProps()
    • 根據props更新state上的meuns
    // 這個方法已經不建議使用
    componentWillReceiveProps(next){
      this.setState({
        menus:next.role.menus
      })
    }
    複製代碼
    • 替代方法
    static getDerivedStateFromProps(nextProps, prevState){
      if (nextProps.role.menus !== prevState.menus) {
        // 額外寫一個newMeuns state來記錄上一個props,在組件渲染的時候傳入這個更新後的newMeuns
        return {
          newMenus:nextProps.role.menus
        };
      } 
      // 不更新state
      return null
    }
    複製代碼
    • getSnapshotBeforeUpdate() (在最近一次渲染輸出(提交到 DOM 節點)以前,render以後調用)

這些⽣命週期被捨棄或新增的緣由?以及新增⽣命週期的參數和做⽤?

  1. 會致使組件沒必要要的更新,父組件渲染即便沒有改變props 也會調用componentWillReceivePorps
  2. 異步渲染時間長會致使componentWillUpdate、componentDidUpdate之間的時間變長,這個過程當中可能發生一些變化,好比用戶行爲致使 DOM 發生了新的變化,這時在 componentWillUpdate獲取的信息可能就不可靠了
  3. 做用static getDerivedStateFromProps(nextProps, prevState)接收兩個參數(它內部你只能訪問到組件上的這兩個參數),第一個爲接收到的新參數,第二是是當前的state。會返回一個對象用來更新state不須要能夠返回null
class Hehe extends React.Component {
  state={
    isRight:false,
    xxx:xxx
  }
  static getDerivedStateFromProps(nextProps, prevState){
    if(nextProps.xxx===prevState.xxx){
      return {
        isRight:true
      }
    }
    return null
  }
}
複製代碼

React⼏個版本(1.6.三、1.6.四、1.7.0)對⽣命週期的相關處理和規劃?

  1. 1.6.3 新舊能夠混用。
  2. 1.6.4 使用舊生命週期,開發者模式下會有警號
  3. 1.7.0 移除舊的生命週期

爲何要把getDerivedStateFromProps設計爲靜態⽅法?

  1. 內部不能拿this,比較純粹,不能用setState(),會在render方法以前被調用,

getDerivedStateFromProps被觸發執⾏的條件有哪些?

  • 組件掛載的時候
  • 接收到新的props
  • 組件卸載時
  • 父組件更新
  • 內部組件執行了state 能夠總結爲一句話,此靜態方法會在render以前被調用,在初始掛載以及後續更新的時候都會被調用。

Derived state的定義是?(如何理解derived state?)

派生一個state,根據傳入的props進行state的更新react

在1.6.3中,setState()不會引發getDerivedFromProps的執⾏,⽽1.6.4.會,緣由是?

聽說是官方失誤bash

1.6.2及其之前升級到1.6.4的⽅案是?

雖然廢棄了這三個生命週期方法,可是爲了向下兼容,將會作漸進式調整。 V16.3 並未刪除這三個生命週期,同時還爲它們新增以 UNSAFE_ 前綴爲別名的三個函數 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()。 在 16.4 版本給出警告將會棄用 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 三個函數異步

1.6.x升級到1.7的⽅案是?

  • 在 17 版本將會刪除 componentWillMount()、componentWillReceiveProps()、componentWillUpdate() 這三個函數,會保留使用 UNSAFE_componentWillMount()、UNSAFE_componentWillReceiveProps()、UNSAFE_componentWillUpdate()
  • 使用 react-lifecycles-compat polyfill
相關文章
相關標籤/搜索