react-改善程序性能

背景

假定有一個父組件叫<Parent>,他有兩個子組件,一個叫<Input>,另一個叫<Table>

import React from 'react'

class Parent extends React.Component {
   initialState = {
       keyword: '',
       ...table所需的所有數據
   }
   state = initialState
   onChange = () => {改變keyword}
   render() {
       return (
           <Input value={keyword} onChange={this.onChange}/>
           <Table {this.state.table}/>
       )
   }
}

在上面這種情況下,只要keyword的值發生了改變,那麼必定會觸發render()方法,這時候會執行Input的函數和Table的函數,

那麼假定Table函數(或類)是個非常複雜的表格,可能是100-500行都有可能,那麼他也重新渲染了,是非常耗費性能的。keyword改變,不應該使得table表格也重新渲染纔對,因爲keyword改變,我table需要的數據完全不變
Table組件:

function Table(props) {
    console.log('無用渲染')
    ...數據初始化忽略
    函數聲明,忽略
    return (
       <div>
          ...忽略
       </div>
    )
}

這是因爲在react中,當一個組件的state或者props發生改變後,必定會執行render方法,,那麼有沒有辦法使得不是table組件需要的數據發生改變時,不重新渲染<Table>組件來提高性能呢?

這裏就可以用到shouldComponentUpdate或者PureComponent以及memo

shouldComponentUpdate

當一個組件的state或者接受到的props發生改變的時候就會觸發該函數,該函數接受兩個參數,返回true或者false

返回false:不執行render方法

返回true:執行render方法

class Table extends Component {
   shouldComponentUpdate(nextProps,nextState) {
      //nextProps:更新後的props,nextState:更新後的state
      if(nextProps !== this.props) {
          return true
      }
      return false
   }
   render() {
      return 
   }
}

props改變後,會對比兩個props,如果兩個props不一致,也就是props發生了改變,會執行render,否則不執行render

React.PureComponent

React.Component和React.PureComponent兩者的區別在於 React.Component 並未實現 shouldComponentUpdate(),而 React.PureComponent 中以淺層對比 prop 和 state 的方式來實現了該函數。React.PureComponent 中的 shouldComponentUpdate() 僅作對象的淺層比較。如果對象中包含複雜的數據結構,則有可能因爲無法檢查深層的差別,產生錯誤的比對結果。僅在你的 props 和 state 較爲簡單時,才使用 React.PureComponent

詳細請看:https://react.docschina.org/docs/react-api.html#reactpurecomponent

import React, {PureComponent} from 'react'
class Table extends PureComponent {
   render() {
      return 
   }
}

React.memo

React.memo 爲高階組件。它與 React.PureComponent 非常相似,但它適用於函數組件,但不適用於 class 組件。

如果想要用函數實現table組件,那麼就可以用memo

const MyComponent = React.memo(function MyComponent(props) {
  /* 使用 props 渲染 */
});

詳細請看:https://react.docschina.org/docs/react-api.html#reactpurecomponent

如果某組件是函數組件,可以使用memo提高性能,如果是類組件,可以使用shouldComponentUpdate或者PureComponent

發佈了42 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章