简体   繁体   English

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

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

How to add a new object to a nested object in reducer ?如何将新对象添加到减速器中的嵌套对象? I have this object the current behavior is a new action simply overrides, the previous action but my goal is to add that array at the end ?我有这个对象,当前行为是一个新动作,只是简单地覆盖了之前的动作,但我的目标是在最后添加该数组? and please any general guidelines how to simply deal with the state ?并请任何一般指导方针如何简单地处理状态? I know the following the state is immutable thus it has to be copied using the spread operator , as you can see in the code I did copy twice still there must by another copy missing but I have no clue where I experimented but no positive.我知道以下状态是不可变的,因此必须使用扩展运算符复制它,正如您在代码中看到的那样,我确实复制了两次仍然必须缺少另一个副本,但我不知道我在哪里进行了实验,但没有任何肯定。 if I add ...(state.item[action.grandParentId] ?? []), under [action.grandParentId] I get really close but it copies the targeted object instead of updating.如果我添加 ...(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, }, ], }, ], }, };

在此处输入图片说明

在此处输入图片说明

From what I can tell you need to also shallow copy the "grandparent", but in this case since you are updating an exiting element of intermediate state you need to map the array to a new array, replacing the element with the matching id.据我所知,您还需要浅复制“祖父母”,但在这种情况下,由于您正在更新处于中间状态的现有元素,因此您需要将数组映射到新数组,并用匹配的 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