使用redux reducer中另一个数组中的项目部分更新数组中所有项目的正确方法?

时间:2018-02-08 18:56:12

标签: reactjs redux react-redux

在Redux中,使用来自另一个数组的项目更新数组中所有项目的最佳做法是仅使用2个数组共有的字段。

例如:

billArrayInStore = [{id, amount, dueDate, summary}, ...] 
newBillArray = [{id, amount, dueDate}, ...]

更新每个帐单(金额,dueDate),但保持“摘要”字段不变。

谢谢:)

2 个答案:

答案 0 :(得分:0)

您可以使用Array.prototype.map

newBillArray = billArrayInStore.map(bill => ({
  ...bill,
  amount: 0, // new amount
  dueDate: '', // new dueDate
}))

答案 1 :(得分:0)

对于billArrayInStore中的每个帐单对象,您希望通过比较ID来查看newBillArray中是否存在相应的帐单对象。如果找到匹配的帐单对象,则将两个帐单合并为一个新对象。这些新的帐单对象存储在一个新数组中,以避免改变原始数据。

由于此解决方案涉及转换现有的帐单对象并将其存储在新数组中,因此它是Array.prototype.map的完美用例。

const updatedBills = billArrayInStore.map(bill => {
    // For each existing bill, check to see if there is a corresponding
    // new bill by comparing bill IDs.
    const newBill = newBillArray.find(newBill => newBill.id === bill.id);

    // If there is a new bill, merge the bills together using spread syntax.
    if (newBill) {
        // Order matters here, you want to spread the new bill last so it
        // can override any properties in the current bill. If the current
        // bill has properties that don't exist in the new bill, they won't
        // be changed.
        return { ...bill, ...newBill };
    }

    // If there isn't a corresponding new bill, the current bill should be
    // returned unmodified.
    return bill;
});

这是一个带有工作示例的片段。



const billArrayInStore = [
  { id: 1, amount: 1000, summary: 'Rent' },
  { id: 2, amount: 50,   summary: 'Internet' },
  { id: 3, amount: 110,  summary: 'Electric' }
];

const newBillArray = [
  { id: 2, amount: 40 },
  { id: 3, amount: 125 }
];

const updatedBills = billArrayInStore.map(bill => {
  const newBill = newBillArray.find(newBill => newBill.id === bill.id);
  if (newBill) {
    return { ...bill, ...newBill };
  }
  return bill;
});

console.log(updatedBills);