当我尝试在 React
中更改状态不可变方式时,它在我调用 setstate
之前更改状态,这让我困惑了 3 天。
这是我在 onClick
事件中调用的方法:
share = (indexFolder) => {
console.log(this.state.folderInfo);
const updateFolderInfo = [...this.state.folderInfo];
updateFolderInfo[indexFolder].isProcessing = false;
//state**is already changed**strong text** when console **
console.log(this.state.folderInfo);
this.setState({
folderInfo : updateFolderInfo,
})
// the setState call do not take effect here
}
这是执行方法的地方:
<Folder key={folder._id}
sharing={this.state.folderIsProcessing}
folder={folder}
delete={() => this.delete(index)}
share={() => this.share(index)} />
//I'm passing share function as props in here ^ , and use it on
//click event in the Folder component .
有什么建议为什么会这样吗?
最佳答案
这里的问题是通过做 const updateFolderInfo = [...this.state.folderInfo];
您实际上是在制作 folderInfo
的浅副本.
这意味着,如果您修改 updateFolderInfo
中的任何项目这是一个对象或数组,您还将在原始 folderInfo
中修改相同的对象/数组。数组。
假设folderInfo
里面只有 JSON,这是一个使用 JSON.stringify
的潜在解决方案和 JSON.parse
创建深拷贝:
share = indexFolder => {
const updatedFolderInfo = JSON.parse(JSON.stringify(this.state.folderInfo));
updatedFolderInfo[indexFolder].isProcessing = false;
this.setState({ folderInfo : updatedFolderInfo });
}
这里有一个小例子,以简化的方式向您展示您当前正在做什么:
array1 = [{id: 1}, {id: 2}, {id: 3}]
array2 = [...array1]
array2[0].id = 100
array2
// [{id: 100}, {id: 2}, {id: 3}]
array1
// [{id: 100}, {id: 2}, {id: 3}]
您可以找到有关浅克隆与深度克隆的更多信息 here .
关于javascript - 在调用 setState 之前 react : why state change when try to change it in immutable way ,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51419488/