[英]Reactjs array mutation
我有这个 function:
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
但我真的不明白为什么这被认为是突变? 我确定我创建了原始数组的副本并对其进行了修改。
请对如何解决此问题有任何建议吗?
展开语法只对 object 或数组进行一级关闭。 任何 object 或超过一级深度的阵列仍将具有相同的参考。 因此,当您使用notActive
数组items
时,您实际上是在使用与GetAccounts
内部相同的引用
正确的更新方法是从 map function 中返回克隆和更新的引用,并使用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 }));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.