React學習之擴展PureRenderMixin(三十三)

PureRenderMixin的出現早於React.PureComponent,該插件屬於歷史保留,現在就使用React.PureComponent吧,這裏也就提一下

如果你的React組件的渲染函數是一個純函數也就是說對於相同的值返回一樣的結果同時不影響元素局,在某些場景下,你可以利用這個插件來極大地提升性能。

var PureRenderMixin = require('react-addons-pure-render-mixin');
React.createClass({
  mixins: [PureRenderMixin],

  render: function() {
    return <div className={this.props.className}>foo</div>;
  }
});

在底層,該插件實現了shouldComponentUpdate,在這裏面,它比較當前的propsstate和接下來的propsstate,當兩者相等的時候返回false,不進行更新。

ES6版本

import PureRenderMixin from 'react-addons-pure-render-mixin';
class FooComponent extends React.Component {
  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
  }

  render() {
    return <div className={this.props.className}>foo</div>;
  }
}`

注意

僅僅是淺比較對象。如果對象包含了複雜的數據結構,深層次的差異可能會產生誤判。僅用於擁有簡單propsstate的組件,或者當你知道很深的數據結構已經變化了的時候使用forceUpdate()。或者,考慮使用immutable objects(不變數據)來幫助嵌套數據快速比較。
[shouldComponentUpdate會跳過更新整個組件子樹。確保所有的子組件也是“純粹的”]這套路不多說。

下一篇將講React中的淺比較

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