简体   繁体   English

React-Redux - 如何处理有效载荷和减速器的嵌套属性实现

[英]React-Redux - how to handle nested property implementation for payloads and reducers

The implementation for nested payload objects and reducers is kinda confusing for me - as i cannot see how it should be implemented.嵌套有效负载对象和减速器的实现对我来说有点令人困惑——因为我看不出它应该如何实现。

Imagine having some user input in UI that outputs a json like this:想象一下,在 UI 中有一些用户输入输出json ,如下所示:

{
 obj1: 'object 1',
 obj2: 'object 2',
 obj3: [{
    nestedObj1: 'nested object 1',
    nestedObj2: 'nested object 1',
    nestedObj3: [{
                deepNestedObj1: 'deep nested obj 1',
                deepNestedObj2: 'deep nested obj 2',
       }],
}

.. and you then have to implement an action creator first og foremost. ..然后你必须首先实现一个动作创建者。 This is what i imagined an action creator would look like:这就是我想象的动作创建者的样子:

export function addItem(obj1, obj2, obj3) {
return {
type:ADD_ITEM,
payload: {
  obj1,
  obj2,
  obj3: [{
    nestedObj1,
    nestedObj2,
    nestedObj3: [{
      deepNestedObj1,
      deepNestedObj2,
    }]
  }]
}}
}

Now my question is: is how the action creator meant to be used when working with deep nested json objects?现在我的问题是:在使用深层嵌套的 json 对象时,动作创建者应该如何使用?

I would strongly recommend against writing an action creator that way.我强烈建议不要以这种方式编写动作创建器。 Per our Redux Style Guide docs page, you should:根据我们的 Redux 样式指南文档页面,您应该:

Also, you should really be usingour official Redux Toolkit package , which will greatly simplify your Redux logic.此外,您真的应该使用我们的官方 Redux 工具包 package ,这将大大简化您的 Redux 逻辑。

I would recommend writing this along the lines of:我建议按照以下方式编写:

const itemsSlice = createSlice({
  name: "items",
  initialState,
  reducers: {
    itemAdded(state, action) {
      const {id1, id2, value} = action.payload;
      if (state[id1]) {
        state[id1][id2].push(value);
      }
    }

  }
})

So, keep the actions as minimal as possible - they should have enough info to describe what happened, and let the reducer figure out how the state should be updated in response.因此,尽可能减少操作 - 他们应该有足够的信息来描述发生的事情,并让减速器弄清楚 state 应该如何更新作为响应。

If cheap solution is what you are looking for you can always copy your properties into a new object.如果您正在寻找便宜的解决方案,您可以随时将您的属性复制到新的 object 中。 Just copy any state into an object before you overwrite properties of said object with user input, at that point call the reducer with new object.只需将任何 state 复制到 object 中,然后用用户输入覆盖所述 object 的属性,然后使用新的 ZA66666CFDE63131C4BEB66 调用减速器

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

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