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
中的浅比较