繁体   English   中英

如何将新对象添加到减速器中的嵌套对象?

[英]How to add a new object to a nested object in reducer?

如何将新对象添加到减速器中的嵌套对象? 我有这个对象,当前行为是一个新动作,只是简单地覆盖了之前的动作,但我的目标是在最后添加该数组? 并请任何一般指导方针如何简单地处理状态? 我知道以下状态是不可变的,因此必须使用扩展运算符复制它,正如您在代码中看到的那样,我确实复制了两次仍然必须缺少另一个副本,但我不知道我在哪里进行了实验,但没有任何肯定。 如果我添加 ...(state.item[action.grandParentId] ?? []),在 [action.grandParentId] 下我会非常接近,但它会复制目标对象而不是更新。

 //initial state items : {} // State Action const AddItem = (select, id, idparent, grandParentId, index) => { dispatch({ type: ADD_ITEM, ITEM: select.item, id: id, idparent: idparent, grandParentId: grandParentId, index: index, }); };

 // ADD ITEM case ADD_ITEM: return { ...state, Items: { ...state.Items, [action.grandParentId]: [ ...(state.exercises[action.grandParentId] ?? []), { [action.idparent]: [ ...(state.Items[action.idparent] ?? []), { index: action.index, id: action.id, item: action.item, }, ], }, ], }, };

在此处输入图片说明

在此处输入图片说明

据我所知,您还需要浅复制“祖父母”,但在这种情况下,由于您正在更新处于中间状态的现有元素,因此您需要将数组映射到新数组,并用匹配的 id 替换该元素。

// ADD ITEM
case ADD_ITEM:
  return {
    ...state,
    Items: {
      ...state.Items,
      [action.grandParentId]: (state.Items[action.grandParentId] ?? []).map(
        item => item[action.idparent]
          ? {
            ...item,
            [action.idparent]: [
              ...(item[action.idparent] ?? []),
              {
                index: action.index,
                id: action.id,
                item: action.item,
              },
            ],
          }
          : item
      ),
    },
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM