【问题标题】:redux - how to remove element in array which is nested to another arrayredux - 如何删除嵌套到另一个数组的数组中的元素
【发布时间】:2021-11-23 23:06:19
【问题描述】:

我想通过发送操作“itemRemoved”来删除项目,我将板的 id 和要删除的元素的 id 传递给它

如何编辑我的 Reducer “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;
  }
};

【问题讨论】:

    标签: arrays reactjs redux


    【解决方案1】:

    我会尝试这样的:

    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;
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2018-02-06
      • 2013-11-22
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 2021-05-02
      • 2022-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多