简体   繁体   English

如何将深度嵌套的 object 添加到 React Reducer 中的深度嵌套数组中?

[英]How to add a deeply nested object to a deeply nested Array in a React Reducer?

I have following React State:我有以下反应 State:

state: {
   objectOne: {
      arrayOne: [
         {
            arrayTwo: [
                {
                   value: 'some value'
                }
            ]         
         }
      ]
   }
}

I am using React useContext and the useReducer hooks.我正在使用 React useContext 和 useReducer 钩子。 What I want to do is to add an object to arrayTwo.我想要做的是将一个 object 添加到 arrayTwo。

What I have tried so far:到目前为止我已经尝试过:

I call a dispatch function with the type of "ADD_NEW_OBJECT" and the payload is an object with some key value pairs in it.我调用类型为“ADD_NEW_OBJECT”的调度 function,有效负载是 object,其中包含一些键值对。

    dispatchFunction({
       type: 'ADD_NEW_OBJECT', 
       payload: {
          value: {
             a: 'this is the ',
             b: 'object I want to add',
          }
          arrayOneIndex: 0, 
          arrayTwoIndex: 0
       }
    });

This is my useReducer case-Statement:这是我的 useReducer 案例语句:

case 'ADD_NEW_OBJECT':
            return {
                ...state,
                objectOne: {
                    ...state.objectOne,
                    arrayOne: [
                        ...state.objectOne.arrayOne,
                        {
                            ...state.objectOne.arrayOne[payload.arrayOneIndex],
                            arrayTwo: [
                                ...state.objectOne.arrayOne[payload.arrayOneIndex].arrayTwo,
                                payload.value
                            ]
                        },
                    ]
                }
            }

Immer is a great library for simplifying this code. Immer是一个用于简化此代码的出色库。 It generates a deep clone of the object passed to it and then you can mutate the clone.它会生成传递给它的 object 的深层克隆,然后您可以对克隆进行变异。

import produce from "immer";

const reducer = produce((draft, action) => {
  switch (action.type) {
    case ADD_NEW_OBJECT:
      draft.objectOne.arrayOne[action.payload.arrayOneIndex][
        action.payload.arrayTwoIndex
      ].push(value);
      return draft;
  }
});

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

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