如何在 shouldComponentUpdate 中比较 prevProps 和 this.props

IT技术 reactjs
2021-04-28 07:24:33

我现在正在使用,shouldComponentUpdate但我不能简单地prevProps.myPropObj == this.state.props.myPropObj进行比较。这是一个对象,我需要进行深入比较。react 是否向我展示了一些方法来告诉我我的props是否改变了?还是他们希望我自己做深度比较?我在想 react 专门从事这种比较,所以它应该告诉我们真/假是否相同?

2个回答

如果 props 是不可变的,你可以使用 react 的shallowCompare. 例如,如果您使用诸如 immutablejs 之类的东西,或者您通过替换而不是改变对象来更改对象,则props可以是不可变的,例如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');
  }
});

React 不提供开箱即用的对象的深度比较。

你可以为此自己构建一些东西。例如,通过向您的对象添加和维护 1 个唯一 ID 来注册更改。

或者在您的应用程序中一致地使用像 immutableJS 这样的库。值得用于具有大型复杂对象的大型复杂应用程序。

确保:对于您的应用程序的功能,您不应该需要shouldComponentUpdate(). React 有自己的引擎,只呈现状态之间的差异。