更新Redux数组中的多个项目

pub*_*t33 1 arrays reactjs redux react-redux

我正在尝试在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'
    }
 ]
Run Code Online (Sandbox Code Playgroud)

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
};
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?有什么建议么?

dev*_*kan 6

另一种选择:

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

forEach返回任何内容,它只是为当前元素执行给定的功能。因此,对于这种情况,map您是您的朋友。

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

const updatedCars =
    state.cars.map(car => action.payload.find(el => el._id === car._id) || car);
Run Code Online (Sandbox Code Playgroud)

  • 您可以将其缩短为`state.cars.map(car => action.payload.find(el => el._id === car._id)|| car)` (2认同)