我正在尝试更新处于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状态时。
我做错了什么?有什么建议吗?
发布于 2018-08-21 23:52:04
另一种选择:
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);发布于 2018-08-21 23:44:58
我将过滤掉action.payload中存在的state中的汽车。然后,我将合并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]https://stackoverflow.com/questions/51952131
复制相似问题