我过去使用过componentDidUpdate()
,它已按预期工作。
然而,这一次,我做到了
componentDidUpdate(prevProps, prevState) {
if (prevState.object.someString !== this.state.object.someString) {
console.log(true);
}
}
和true
从未登录。我将两个状态对象记录到控制台,发现它们完全相同:当前状态。
这是一个错误吗?我在这里错过了什么?
谢谢。
编辑:我试图用componentWillUpdate(nextProps, nextState)
做同样的事情,再次,他们是同一个对象。
编辑2:我正在改变状态:
modifyObject = (field, value) => {
const { object } = this.state;
object[field] = value;
this.setState({ object });
}
在添加的代码中,您通过仅更改对象上的属性来改变引用对象。这意味着最终nextProps
和previousProps
在本质上指的是相同的参考。
因此,你的componentDidUpdate
没有发现差异就不足为奇了。
你应该做的是创建一个新版本的对象,并使用它来设置状态,如:
this.setState({ object: { ...object, [field]: value } })
或者,如果你没有传播运营商,那就像
this.setState( { object: Object.assign({}, object, { [field]: value }) } );
注意:
如果shouldComponentUpdate()返回false,则不会调用componentDidUpdate()。 ref:https://reactjs.org/docs/react-component.html#componentdidupdate
shouldComponentUpdate(nextProps, nextState) {
if (this.state.someString !== nextState.someString) {
return true;
}
return false;
}
componentDidUpdate(prevProps, prevState) {
if (prevState.someString !== this.state.someString) {
console.log(true);
}
}
在某些情况下,当你使用shouldComponentUpdate
时,更好地使用像lodash isEqual方法来深入比较你的状态/道具:
shouldComponentUpdate(nextProps, nextState) {
return !isEqual(this.state, nextState);
}
如果你有复杂的道具/状态,这将提高你的表现,因为没有浪费的渲染发生
谢谢Icepickle的评论,这解决了这个问题。
而不是做
modifyObject = (field, value) => {
const { object } = this.state;
object[field] = value;
this.setState({ object });
}
我做到了
modifyObject = (field, value) => {
const { object } = this.state;
this.setState({ object: { ...object, [field]: value } });
}
再次感谢。