我现在正在使用,shouldComponentUpdate但我不能简单地做prevProps.myPropObj == this.state.props.myPropObj比较.这是一个对象,我需要进行深入的比较.反应是否向我揭示了一些方法告诉我我的道具是否改变了?或者他们希望我自己做深度比较?我认为反应专门用于比较,所以它应该告诉我们真假是否相同或不相反?
如果道具是不可变的,你可以使用react's 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>;
}
}
Run Code Online (Sandbox Code Playgroud)
对于非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');
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12006 次 |
| 最近记录: |