简体   繁体   中英

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:

{
 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?

I would strongly recommend against writing an action creator that way. Per our Redux Style Guide docs page, you should:

Also, you should really be usingour official Redux Toolkit package , which will greatly simplify your Redux logic.

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.

If cheap solution is what you are looking for you can always copy your properties into a new 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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