更新Redux数组中的多个项目

时间:2018-08-21 15:32:31

标签: arrays reactjs redux react-redux

我正在尝试以redux状态更新对象数组,

汽车恢复状态

cars:  [
  {
    _id:"5b61b782719613486cdda7ec",
    car: "BMW",
    year: '2015'
   },
   {
      _id:"5b61b782719613486cdda7e1",
      car: "Toyota",
      year: '2015'
    },
    {
      _id:"5b61b782719613486cdda7e2",
      car: "Honda",
      year: '2015'
    },
    {
      _id:"5b61b782719613486cdda7e3",
      car: "Audi",
      year: '2015'
    }
 ]

action.payload数组

 action.payload :      
   [
    {
      _id:"5b61b782719613486cdda7ec",
      car: "BMW",
      year: '2019'
    },
    {
      _id:"5b61b782719613486cdda7e3",
      car: "Audi",
      year: '2019'
    }
  ]


case UPDATE_CARS:
  const updatedCars = state.cars.map((car) => {
  action.payload.forEach((newCars, index) => {
    if (car._id !== newCars._id) {
      //This is not the item we care about, keep it as is
      return car;
    } else {
      //Otherwise, this is the one we want to return an updated value
      return { ...car, ...newCars };
    }
  });
});

return {
  ...state,
  cars: updatedCars,
  loading: false
};

如您所见,仅当项目处于redux状态时,我才尝试更新redux数组中的多个项目。

我在做什么错?有什么建议么?

2 个答案:

答案 0 :(得分:5)

另一种选择:

const updatedCars = state.cars.map( car => {
  const found = action.payload.find( el => el._id === car._id );
  return found ? found : car;
});

forEach不是return anything,它只是为当前元素执行给定的功能。因此,在map是您的朋友的情况下。

即使@Luke M Willis在评论中提供了一个更短,更好的版本:

const updatedCars =
    state.cars.map(car => action.payload.find(el => el._id === car._id) || car);

答案 1 :(得分:1)

我将过滤state中存在的action.payload的汽车。然后,我将合并action.payload,并过滤state,如下所示。

case UPDATE_CARS:
  const updatedCarIds = action.payload.map(o => o.id);
  const notUpdatedCars = state.cars.filters(car => !updatedCarIds.includes(car.id))
  return [...notUpdatedCars, ...action.payload]