componentDidUpdate中的prevState是currentState吗? [英] prevState in componentDidUpdate is the currentState?
问题描述
我过去曾经使用过componentDidUpdate()
,它的工作符合预期.
I've used componentDidUpdate()
in the past and it has worked as expected.
但是这次,我做到了
componentDidUpdate(prevProps, prevState) {
if (prevState.object.someString !== this.state.object.someString) {
console.log(true);
}
}
和true
从未记录.我将两个状态对象都记录到控制台,发现它们是完全相同的:当前状态.
and true
is never logged. I logged both state objects to the console and found out they are exactly the same one: the current state.
这是一个错误吗?我在这里想念什么?
Is this a bug? What am I missing here?
谢谢.
我试图对componentWillUpdate(nextProps, nextState)
做同样的事情,同样,它们是同一对象.
I tried to do the same thing with componentWillUpdate(nextProps, nextState)
and again, they're the same object.
我正在通过以下方式更改状态:
Edit 2: I'm changing the state by doing:
modifyObject = (field, value) => {
const { object } = this.state;
object[field] = value;
this.setState({ object });
}
推荐答案
在添加的代码中,您仅通过更改对象的属性即可对其进行突变.这意味着最终nextProps
和previousProps
本质上是指相同的引用.
In the added code, you are mutating a reference object by changing just a property on the object. This means that eventually nextProps
and previousProps
in essence refer to the same reference.
因此,您的componentDidUpdate
没有发现差异也就不足为奇了.
So it is no surprise that your componentDidUpdate
didn't find a difference.
您应该做的是创建对象的新版本,然后使用该对象来设置状态,例如:
What you should do is create a new version of your object, and use that one to set the state, like:
this.setState({ object: { ...object, [field]: value } })
或者如果您没有传播算子,类似
or if you don't have the spread operator, something like
this.setState( { object: Object.assign({}, object, { [field]: value }) } );
这篇关于componentDidUpdate中的prevState是currentState吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!