Javascript 反应JS阵列突变
我有这个功能:Javascript 反应JS阵列突变,javascript,reactjs,Javascript,Reactjs,我有这个功能: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts] const notActive = shallowCopyOfWalletsArray.filter(user => user.active !== true); let newArr
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
但我真的不明白为什么这被认为是一种变异?我确信我创建了原始数组的副本并对其进行了修改
请给出解决方法的建议?Spread语法只对对象或数组进行一级关闭。任何深度超过一级的对象或数组仍将具有相同的引用。因此,当您使用
notActive
arrayitems
时,您实际上使用的是GetAccounts
正确的更新方法是从map函数中返回克隆和更新的引用,并使用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 }));
}
在映射数组时对其进行变异不是一种好的做法,因为它可能会有意外的输出。您能建议一些解决方法吗?您创建了数组的浅拷贝,而不是项,然后您正在变异项。您还将承诺数组设置为
onlyNotActive
状态,这是真的吗?这能回答你的问题吗@谢谢你指出这一点。我更新了我的答案我非常感谢你的回答和解释!