react性能優化


前面的話

  本文將詳細介紹react性能優化

 

避免重復渲染

  當一個組件的props或者state改變時,React通過比較新返回的元素和之前渲染的元素來決定是否有必要更新實際的DOM。當他們不相等時,React會更新DOM。

  在一些情況下,組件可以通過重寫這個生命周期函數shouldComponentUpdate來提升速度, 它是在重新渲染過程開始前觸發的。 這個函數默認返回true,可使React執行更新:

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

  如果知道在某些情況下組件不需要更新,可以在shouldComponentUpdate內返回false來跳過整個渲染進程,該進程包括了對該組件和之后的內容調用render()指令

  如果想讓組件只在props.color或者state.count的值變化時重新渲染,可以像下面這樣設定shouldComponentUpdate

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

【pureComponent】

  在以上代碼中,shouldComponentUpdate只檢查props.colorstate.count的變化。如果這些值沒有變化,組件就不會更新。當組件變得更加復雜時,可以使用類似的模式來做一個“淺比較”,用來比較屬性和值以判定是否需要更新組件。這種模式十分常見,因此React提供了一個輔助對象來實現這個邏輯 - 繼承自React.PureComponent。以下代碼可以更簡單的實現相同的操作:

class CounterButton extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

  大部分情況下,可以使用React.PureComponent而不必寫自己的shouldComponentUpdate,它只做一個淺比較。但是由於淺比較會忽略屬性或狀態突變的情況,此時不能使用它

 

避免突變

  PureComponent將會在this.props.words的新舊值之間做一個簡單的比較。由於代碼中words數組在WordAdderhandleClick方法中被改變了,盡管數組中的實際單詞已經改變,this.props.words的新舊值還是相等的,因此即便ListOfWords具有應該被渲染的新單詞,它還是不會更新。

  handleClick() {
    // This section is bad style and causes a bug
    const words = this.state.words;
    words.push('marklar');
    this.setState({words: words});
  }

  避免此類問題最簡單的方式是避免使用值可能會突變的屬性或狀態。例如,上面例子中的handleClick應該用concat重寫成:

handleClick() {
  this.setState(prevState => ({
    words: prevState.words.concat(['marklar'])
  }));
}

  或者使用展開運算符

handleClick() {
  this.setState(prevState => ({
    words: [...prevState.words, 'marklar'],
  }));
};

  也可以用相似的方式重寫可以會突變的對象。例如,假設有一個叫colormap的對象,我們想寫一個把colormap.right改變成'blue'的函數,我們應該寫:

function updateColorMap(colormap) {
  colormap.right = 'blue';
}

  想要實現代碼而不污染原始對象,我們可以使用Object.assign方法

function updateColorMap(colormap) {
  return Object.assign({}, colormap, {right: 'blue'});
}

  或者使用擴展運算符

function updateColorMap(colormap) {
  return {...colormap, right: 'blue'};
}

 

immutable

  Immutable.js是解決這個問題的另一種方法。它通過結構共享提供不可突變的,持久的集合

  1、不可突變:一旦創建,集合就不能在另一個時間點改變

  2、持久性:可以使用原始集合和一個突變來創建新的集合。原始集合在新集合創建后仍然可用

  3、結構共享:新集合盡可能多的使用原始集合的結構來創建,以便將復制操作降至最少從而提升性能

  不可突變數據使得變化跟蹤很方便。每個變化都會導致產生一個新的對象,因此只需檢查索引對象是否改變。例如,在這個常見的JavaScript代碼中:

const x = { foo: 'bar' };
const y = x;
y.foo = 'baz';
x === y; // true

  雖然y被編輯了,但是由於它與x索引了相同的對象,這個比較會返回true。可以使用immutable.js實現類似效果:

const SomeRecord = Immutable.Record({ foo: null });
const x = new SomeRecord({ foo: 'bar' });
const y = x.set('foo', 'baz');
x === y; // false

  在這個例子中,x突變后返回了一個新的索引,因此我們可以安全的確認x被改變了

  還有兩個庫可以幫助我們使用不可突變數據:seamless-immutable 和immutability-helper。 實現shouldComponentUpdate時,不可突變的數據結構幫助我們輕松的追蹤對象變化。這通常可以提供一個不錯的性能提升

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM