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
,在這裏面,它比較當前的props
、state
和接下來的props
、state
,當兩者相等的時候返回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>;
}
}`
注意
僅僅是淺比較對象。如果對象包含了複雜的數據結構,深層次的差異可能會產生誤判。僅用於擁有簡單props
和state
的組件,或者當你知道很深的數據結構已經變化了的時候使用forceUpdate()
。或者,考慮使用immutable objects
(不變數據)來幫助嵌套數據快速比較。
[shouldComponentUpdate
會跳過更新整個組件子樹。確保所有的子組件也是“純粹的”]這套路不多說。
下一篇將講
React
中的淺比較