是否可以仅更新对象的数组状态?

时间:2019-04-07 18:04:15

标签: javascript reactjs ecmascript-6

我想知道是否有任何文档或参考可以帮助我了解如何更新对象数组的状态(无重复项)。

我的状态如下:

accounts: [
    { name: ‘mike’ },
    { name: ‘tee’ },
    { name: ‘ralf’ },
    { name: ‘candy’ },
    { name: ‘bon’ },
    { name: ‘salm’ },
    { name: ‘shark’ },
    { name: ‘tof’ },
    { name: ‘hulk’ },
    { name: ‘zar’ },
    { name: ‘blake’ },
  ],

即将到来的数组是这样的:

accounts: [
    { name: 'mike’, balance: ’1000’},
    { name: 'tee’, balance: ’235345’},
    { name: 'zar’, balance: ’3455’},
    { name: 'candy’, balance: ’567567’},
    { name: 'tee’, balance: ’8767’},
    { name: 'salm', balance: ’234’},
    { name: 'blake', balance: ’134’},
  ],

因此setState上的更新状态将如下所示:

accounts: [
    { name: 'mike’, balance: ’1000’},
    { name: 'tee’, balance: ’235345’},
    { name: ‘ralf’ },
    { name: 'candy’, balance: ’567567’},
    { name: ‘bon’ },
    { name: 'salm', balance: ’234’},
    { name: ‘shark’ },
    { name: ‘tof’ },
    { name: ‘hulk’ },
    { name: 'zar’, balance: ’3455’},
    { name: 'blake', balance: ’134’},
  ],

我尝试使用prevState.accounts.concat(accounts),但是它只会添加重复项。

2 个答案:

答案 0 :(得分:2)

根据条件查找对象,然后在使用Array#find方法查找元素和使用Object.assign方法将值复制到现有对象的情况下更新值。

accounts.forEach( o => {
   let oldObj = prevState.accounts.find(o1 => o1.name === o.name);
   Object.assign(oldObj, o)
})

最终代码如下:

this.setState(prevState => {
  newAccounts.forEach(o => {
    let oldObj = prevState.accounts.find(o1 => o1.name === o.name);
    Object.assign(oldObj, o)
  })
  return prevState.accounts
});

通过创建新数组来实现Oneliner解决方案。

this.setState(prevState => newAccounts.map(o => Object.assign(prevState.accounts.find(o1 => o1.name === o.name), o)));

// if you don't want to mutate original object in previous state then

this.setState(prevState => newAccounts.map(o => Object.assign({}, prevState.accounts.find(o1 => o1.name === o.name), o)));

// or with ES6 spread syntax
this.setState(prevState => newAccounts.map(o => ({ ...prevState.accounts.find(o1 => o1.name === o.name), ...o }))));

答案 1 :(得分:1)

如果您的新状态帐户始终将是先前状态帐户值的子集。您可以使用类似这样的

this.state = {
    accounts : [
        { name: 'mike' },
        { name: 'tee' },
        { name: 'ralf' },
        { name: 'candy' },
        { name: 'bon' },
        { name: 'salm' },
        { name: 'shark' },
        { name: 'tof' },
        { name: 'hulk' },
        { name: 'zar' },
        { name: 'blake' },
    ]
}
const newAccounts = [
    { name: 'mike', balance: 1000},
    { name: 'tee', balance: 235345},
    { name: 'zar', balance: 3455},
    { name: 'candy', balance: 567567},
    { name: 'tee', balance: 8767},
    { name: 'salm', balance: 234},
    { name: 'blake', balance: 134},
]
this.setState({accounts: this.state.accounts.map (x => ({...x, ...newAccounts.find(y => y.name === x.name)}))});

您可以使用Array.find在新帐户中查找旧状态帐户的值,然后使用...Object.assign合并属性。