Reactjs 数组突变

IT技术 javascript reactjs
2021-05-27 00:55:31

我有这个功能:

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

但我真的不明白为什么这被认为是突变?我确定我创建了原始数组的副本并对其进行了修改。

关于如何解决这个问题的任何建议?

1个回答

Spread 语法只是对对象或数组进行一级关闭。任何深度超过一层的对象或数组仍将具有相同的引用。因此,当您使用notActivearray 时items,您实际上是在处理内部的相同引用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 }));
    
  }