我想通过两个 for 循环为一个对象数组设置 State,其键/属性之一是一个数组。
我一直在尝试几种解决方案(没有一个对我有用),下面是其中之一。如果我搬家var secondArr = [];
在循环内,所有用户的整个文件都会发送给每个用户
state = {
users: [
index: "",
firstName: "",
files: [],
];
}
handleDate = async () => {
var firstArr = [];
var secondArr = [];
//firstCount means the user number in the database
for (var i = 0; i < firstCount; i++) {
// i get some result from a call called file
//secondCount means the number of files for each user in the database
for (var j = 0; j < secondCount; j++) {
// i get some result from called file
//this also can be secondArr.push({index:result[0], files:file})
secondArr.push(file); < ------------- I guess the problem is here, the right files needs to be save in the array of the right user
}
// i get an array as a result from a call called result
firstArr.push({ index: result[0], firstName: result[1], files: secondArr });
this.setState({ users: firstArr });
}
}
最佳答案
我发现有两个错误,它们可能会导致您意想不到的行为。
首先,您应该在第一个循环内声明内部数组变量,否则您可能会继续跨多个用户添加文件。这可能是也可能不是您的意图。
其次,您在循环中调用 setState
,这不会按您的预期工作,因为:
setState
调用实际上是由 React 进行批处理的。他们不会开火 立即地。- 从第二次 setState 调用开始,您正在改变状态 病房,您正在更改相同数组。 React 可能决定不这样做 重新渲染第二次调用,因为它看到相同的数组。我会更新 这个答案稍后会提供有关不变性的资源。
根据我建议的更改,您的代码应如下所示:
handleDate = async()=>{
var firstArr=[];
for (var i = 0; i < firstCount; i++) {
// i get some result from a call called file
var secondArr=[];
for (var j = 0; j < secondCount; j++) {
// i get some result from called file
secondArr.push(file);
}
// i get an array as a result from a call called result
firstArr.push({index:result[0], firstName:result[1], files:secondArr});
}
this.setState({users:firstArr});
}
关于javascript - 通过两个for循环setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52308712/