[英]How to use reducer in neasted array
trying to delete id:2 car from my mongodb database. 试图从我的mongodb数据库中删除id:2 car。 using react redux, my question is how to check dispatch id equal to car id in reducer? 使用React Redux,我的问题是如何在Reducer中检查调度ID等于汽车ID?
button <button onClick={this.handleDeleteCar(carID : data.id)>delete</button>
按钮 <button onClick={this.handleDeleteCar(carID : data.id)>delete</button>
data log 数据记录
carview:
[
{ id: 5c7496f0def4602bf413ea9a,
parentId: 5c7496f0def4602bf413ea97,
car: [
{
id: 2,
name: bmw
},
{
id:3,
name: amg
}
]
}
]
reducer 减速器
case carConstants.car_DELETE_REQUEST:
return {...state,items: state.items.map(car =>car.id === action.id
? { ...car, deleting: true }
: car
)
};
Use Array.prototype.filter() 使用Array.prototype.filter()
return {
...state,
items: state.items.filter((car) => car.id !== action.id)
}
EDIT: 编辑:
In your case, you can use an Array.prototype.filter nested inside an Array.prototype.map: 您可以使用嵌套在Array.prototype.map中的Array.prototype.filter:
return {
...state,
carView: state.carView.map((view) => {
return {
...view,
car: view.car.filter(({ id }) => id !== action.id)
}
})
}
This can become quickly messy if you deal with deeply nested objects and it's a good idead to try to keep your state normalized in redux 如果您处理深度嵌套的对象,这可能会很快变得混乱,建议您在redux中保持状态规范化为好主意
Above answer using Array.filter is a good one, but if that won't fit your use case you can use a nested findIndex check. 上面的答案使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.