[英]Can anyone explain why my state is getting updated even when i dont set it manually
So I just spent an hour debugging this code and finally got it to work, but I would want to know why this happened in the first place.所以我只花了一个小时调试这段代码,终于让它工作了,但我想知道为什么会发生这种情况。 I have a function that takes a value from my state, operates on it and saves the output in another variable in the state.
我有一个函数,它从我的状态中获取一个值,对其进行操作并将输出保存在状态中的另一个变量中。 This is the fuction:
这是功能:
getFolderNames = async () => {
const promises = this.state.rows.map(async item => {
if (item[".tag"] == "folder" && item.name.length > 20) {
item.name = await getFolderName(item.name);
return item;
} else return item;
});
const result = await Promise.all(promises);
this.setState({
rowsToDisplay: result
});
};
when i run this function, it was updating both the rows and rowsToDisplay to the result variable when i was only calling setState on only one of them.当我运行这个函数时,当我只在其中一个上调用 setState 时,它正在将 rows 和 rowsToDisplay 更新为结果变量。
Changing the function as below solves the issue but I would like to know why.更改如下功能可以解决问题,但我想知道原因。
getFolderNames = async () => {
const promises = this.state.rows.map(async item => {
if (item[".tag"] == "folder" && item.name.length > 20) {
let item2 = {
...item
};
item2.name = await getFolderName(item.name);
return item2;
} else return item;
});
const result = await Promise.all(promises);
this.setState({
rowsToDisplay: result
});
};
It's because of how JavaScript handles variables.这是因为 JavaScript 处理变量的方式。 When you set a variable to an array or object, it doesn't make a new object but rather just references the original array/object.
当您将变量设置为数组或对象时,它不会创建新对象,而只是引用原始数组/对象。
As such, if you set a variable to equal some object, and then set a property of that variable, the original object will also be updated.因此,如果您将变量设置为等于某个对象,然后设置该变量的属性,则原始对象也将被更新。 Check this snippet for an example.
检查此代码段以获取示例。
var foo = {changed: false}; var bar = foo; bar.changed = true; console.log("foo", foo.changed) console.log("bar", bar.changed)
You can read more about the subject here: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0您可以在此处阅读有关该主题的更多信息: https : //codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0
I hope this helps you in the future, since I know I also spent many hours banging my head against exactly the sort of cases you described in your original question.我希望这在将来对您有所帮助,因为我知道我也花了很多时间来解决您在原始问题中描述的那种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.