[英]Object assign and spread operator mutate React state?
I wonder if I did something wrong because as far as I know: Object.assign and spread operator will create new object, therefore we can avoid mutate the internal state with is a bad practice.我想知道我是否做错了什么,因为据我所知: Object.assign 和 spread 运算符将创建新对象,因此我们可以避免改变内部状态是一种不好的做法。 But in my project those two don't seem to work.
但在我的项目中,这两个似乎不起作用。
First, in my constructor, I setup the state as below:首先,在我的构造函数中,我将状态设置如下:
this.state = {
article: {
title: "",
alias: "",
category: "JAVA",
steps: [
{
stepId: 1,
title: "Dummy title",
description: "The quick brown fox jump over the lazy dog",
length: 30
}
]
},
description: "",
newStep: {
title: "",
length: 0
}
}
Later, I add an addStep() function:后来,我添加了一个 addStep() 函数:
addStep() {
console.log(this.state.article.steps);
let article = { ...this.state.article };
article.steps.push({
stepId: _.last(this.state.article.steps).stepId + 1,
title: this.state.newStep.title,
length: this.state.newStep.length,
description: "",
});
console.log(this.state.article.steps);
}
As you can see this.state.article.steps has been mutated.如您所见, this.state.article.steps已发生变异。 The same goes for Object.assign.
Object.assign 也是如此。 Finally I decide to use and that solved my problem.
最后我决定使用,这解决了我的问题。
let article = JSON.parse(JSON.stringify(this.state.article));
Object.assign{}
and object spread won't deep clone an object. Object.assign{}
和 object spread 不会深度克隆对象。
It will mutate steps
.它会改变
steps
。
It is discussed in the following thread:它在以下线程中讨论:
How do I correctly clone a JavaScript object? 如何正确克隆 JavaScript 对象?
let article = { ...this.state.article };
is only making a shallow copy of the object.只是制作对象的浅拷贝。 You can manually make new child keys with something like:
您可以使用以下内容手动制作新的子键:
let article = {
...this.state.article,
steps: [...this.state.article.steps]
};
There are many ways to deal with the problem of trying to clone a deeply nested object.有很多方法可以处理试图克隆深度嵌套对象的问题。 This is just one of them.
这只是其中之一。
You could spread the original state this.state.article
and overwrite the nested values (like steps
) with another spread.您可以传播原始状态
this.state.article
并用另一个传播覆盖嵌套值(如steps
)。
let article = {
...this.state.article,
steps: [...this.state.article.steps]
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.