试图从我的mongodb数据库中删除id:2汽车。使用React Redux,我的问题是如何在Reducer中检查与汽车ID相等的调度ID?
按钮
<button onClick={this.handleDeleteCar(carID : data.id)>delete</button>
数据日志
carview:
[
{ id: 5c7496f0def4602bf413ea9a,
parentId: 5c7496f0def4602bf413ea97,
car: [
{
id: 2,
name: bmw
},
{
id:3,
name: amg
}
]
}
]
减速器
case carConstants.car_DELETE_REQUEST:
return {...state,items: state.items.map(car =>car.id === action.id
? { ...car, deleting: true }
: car
)
};
答案 0 :(得分:4)
return {
...state,
items: state.items.filter((car) => car.id !== action.id)
}
编辑:
您可以使用嵌套在Array.prototype.map中的Array.prototype.filter:
return {
...state,
carView: state.carView.map((view) => {
return {
...view,
car: view.car.filter(({ id }) => id !== action.id)
}
})
}
如果您处理深度嵌套的对象,这可能会很快变得混乱,try to keep your state normalized in redux
答案 1 :(得分:0)
以上使用Array.filter的答案是一个很好的答案,但是如果不适合您的用例,则可以使用嵌套的findIndex检查。
let state = [
{ id: "5c7496f0def4602bf413ea9a",
parentId: "5c7496f0def4602bf413ea97",
car: [
{
id: 4,
name: "bmw"
},
{
id:5,
name: "amg"
}
]
},
{ id: "5c7496f0def4602bf413ea9a",
parentId: "5c7496f0def4602bf413ea97",
car: [
{
id: 2,
name: "bmw"
},
{
id:3,
name: "amg"
}
]
}
];
const action = { type: 'example', id: 2 }
const index = state.findIndex(({car}) => car.findIndex(({id}) => id === action.id) !== -1);
if (index === -1) {
// you would probably return current state here realistically
throw new Error('no index');
}
console.log(index);
state = [ ...state.slice(0, index), ...state.slice(index + 1)];
console.log(state);