![](/img/trans.png)
[英]How to format neasted json array depends on conditions request json for api
[英]How to use reducer in neasted array
試圖從我的mongodb數據庫中刪除id:2 car。 使用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
)
};
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)
}
})
}
如果您處理深度嵌套的對象,這可能會很快變得混亂,建議您在redux中保持狀態規范化為好主意
上面的答案使用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.