我有这个功能:
setNotActiveWalletsList = () => {
const { GetAccounts } = this.props;
let shallowCopyOfWalletsArray = [...GetAccounts]
const notActive = shallowCopyOfWalletsArray.filter(user => user.active !== true);
let newArr = notActive.map(item => {
return decryptAccountInformation(item).then(result => {
!result.address ? null : item.address = result.address
})
});
this.setState({ onlyNotActive: newArr });
}
GetAccounts 是一个对象数组
问题是,我的一位同事告诉我,我正在用这一行改变数组:
!result.address ? null : item.address = result.address
但我不太明白为什么这被认为是突变?我确定我创建了原始数组的副本并对其进行了修改。
请问有什么解决此问题的建议吗?
最佳答案
扩展语法仅对对象或数组进行一级关闭。任何深度超过一层的对象或数组仍将具有相同的引用。因此,当您使用 notActive
数组 items
时,您实际上是在处理 GetAccounts
正确的更新方法是从映射函数中返回克隆和更新的引用,并使用 Promise.all
来处理异步调用
setNotActiveWalletsList = () => {
const { GetAccounts } = this.props;
let shallowCopyOfWalletsArray = [...GetAccounts]
const notActive = shallowCopyOfWalletsArray.filter(user => user.active !== true);
let promises = notActive.map(item => {
return decryptAccountInformation(item).then(result => {
return !result.address ? item : {...item, address: result.address}
})
});
Promise.all(promises).then(newArr => this.setState({ onlyNotActive: newArr }));
}
关于javascript - Reactjs 数组突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66585490/