Redux - How to add entry to array in reducer

后端 未结 1 1407
鱼传尺愫
鱼传尺愫 2021-01-01 14:25

I stuck with this bit and I can\'t progress - I guess solution is simple but I can\'t figure out. I\'m trying to add entry in reducer so data in in would look something this

相关标签:
1条回答
  • 2021-01-01 15:14

    If you're trying to add an element to the end of the entryName array you should be doing:

    return {
      ...state,
      [entryId]: {
        ...state[entryId],
        [entryName]: [
          ...state[entryId][entryName],
          uniqueEntry
        ]
      }
    };
    

    ES6 spread with arrays works like this:

    const array1 = [1, 2, 3];
    const array2 = [4, 5, 6];
    const eight = 8;
    
    const newArray = ['stuff', ...array1, 'things', ...array2, ...[7, eight], 9];
    console.log(newArray); // ["stuff", 1, 2, 3, "things", 4, 5, 6, 7, 8, 9]
    

    Check out this gist which has an example of something very similar to what you're doing.

    I found this set of examples extremely helpful as well. A lot of great stuff in here:

    https://github.com/sebmarkbage/ecmascript-rest-spread

    Update:

    If entryName is initialized to undefined like you say in your comment, you could do this:

    return {
      ...state,
      [entryId]: {
        ...state[entryId],
        [entryName]: [
          ...state[entryId][entryName] || [],
          uniqueEntry
        ]
      }
    };
    

    I think this is a pretty great example of how painful it can be working with React/redux using a heavily nested data structure. FWIW, it's been recommended to me many times to flatten your state as much as possible.

    0 讨论(0)
提交回复
热议问题