1. 程式人生 > >react(6) shouldComponentUpdate避免元件重複或者無意義渲染

react(6) shouldComponentUpdate避免元件重複或者無意義渲染

shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState)

使用shouldComponentUpdate()以讓React知道當前狀態或屬性的改變是否不影響元件的輸出。預設行為是在每一次狀態的改變重渲,在大部分情況下你應該依賴於預設行為。

當接收到新屬性或狀態時,shouldComponentUpdate() 在渲染前被呼叫。預設為true。該方法並不會在初始化渲染或當使用forceUpdate()時被呼叫。

當他們狀態改變時,返回false 並不能阻止子元件重渲。

當前,若shouldComponentUpdate()

返回false,而後UNSAFE_componentWillUpdate()render(), 和 componentDidUpdate()將不會被呼叫。注意,在未來React可能會將shouldComponentUpdate()作為一個線索而不是一個嚴格指令,返回false可能仍然使得元件重渲。

在觀察後,若你判定一個具體的元件很慢,你可能需要調整其從React.PureComponent繼承,其實現了帶有淺屬性和狀態比較的shouldComponentUpdate()。若你確信想要手寫,你可能需要用this.propsnextProps以及this.state 和 nextState

比較,並返回false以告訴React更新可以被忽略。

shouldComponentUpdate是react提供的生命週期函式,他發生在接收到新的props的時候。
簡單介紹一下各個生命週期函式。

componentWillMount:元件掛載之前執行,只執行一次

componentDidMount: 元件渲染完成,只執行一次

=======================================================

componentWillRecevieProps: 元件將要接收新的props執行

shouldComponentUpdate: 判斷元件是否應該重新渲染,預設是true

componentWillUpdate: 元件將要重新渲染

componentDidUpdate: 元件重新渲染完成

=======================================================

componentWillUnmount: 解除安裝元件

下面是簡單例子

 shouldComponentUpdate避免元件重複或者無意義渲染

shouldComponentUpdate(nextProps) {
    if(JSON.stringify(nextProps) == JSON.stringify(this.props)) {
      return false
    }else {
      return true
    }
  }