小编典典

如何在shouldComponentUpdate中将prevProps与this.props进行比较

reactjs

我正在使用,shouldComponentUpdate但是我不能简单地prevProps.myPropObj == this.state.props.myPropObj进行比较。这是一个对象,我需要进行深度比较。反应会告诉我一些方法来告诉我我的道具是否改变吗?还是他们希望我自己进行深度比较?我当时以为react擅长于这种比较,所以它应该告诉我们对/错是否成立?


阅读 575

收藏
2020-07-22

共1个答案

小编典典

如果道具是不可变的,则可以使用react的shallowCompare。例如,如果您使用诸如immutablejs之类的道具,或者通过替换而不是对其进行突变来更改对象,则道具可能是不可变的。const prop = Object.assign({}, prop, { changedValues: 'value' });

var shallowCompare = require('react-addons-shallow-compare');
export class SampleComponent extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

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

对于非es6,非节点环境:

相当于var shallowCompare = require('react-addons-shallow-compare');var shallowCompare = React.addons.shallowCompare;如此完整的例子是:

var SampleComponent = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
     return React.addons.shallowCompare(this, nextProps, nextState);
  },
  render: function() {
     return React.createElement('div', {className:this.props.className}, 'foo');
  }
});
2020-07-22