redux -如何删除嵌套到另一个数组中的元素



我想通过发送动作"itemRemoved"来删除项目,我传递了板的id和要删除的元素的id

如何编辑我的减速器"case ITEM_REMOVED"?

const initialState = {
boards: [
{
id: 1,
title: "1",
items: [
{ id: 1, title: "1" },
{ id: 2, title: "2" },
],
},
{
id: 2,
title: "2",
items: [
{ id: 3, title: "3" },
{ id: 4, title: "4" },
{ id: 5, title: "5" },
],
},
],
};
const actions = {
itemRemoved: (boardId, itemId) =>
({ type: ITEM_REMOVED, boardId, itemId }),
}
const boardsReducer = (state = initialState, action) => {
switch (action.type) {
case ITEM_REMOVED:
return {
...state,
boards: [] // <-- ??????????
};
default:
return state;
}
};

我将尝试这样做:

const boardsReducer = (state = initialState, action) => {
switch (action.type) {
case ITEM_REMOVED:
return {
...state,
boards: state.boards.map(b => {
if (b.id !== action.boardId) {
return b
}

const newB = {...b}
newB.items = newB.items.filter(i => i !== action.itemId)
return newB;
})
};
default:
return state;
}
};

相关内容