How to update single value inside specific array item in redux

前端 未结 8 1400
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 01:55

I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page.

8条回答
  •  借酒劲吻你
    2020-11-28 02:33

    I believe when you need this kinds of operations on your Redux state the spread operator is your friend and this principal applies for all children.

    Let's pretend this is your state:

    const state = {
        houses: {
            gryffindor: {
              points: 15
            },
            ravenclaw: {
              points: 18
            },
            hufflepuff: {
              points: 7
            },
            slytherin: {
              points: 5
            }
        }
    }
    

    And you want to add 3 points to Ravenclaw

    const key = "ravenclaw";
      return {
        ...state, // copy state
        houses: {
          ...state.houses, // copy houses
          [key]: {  // update one specific house (using Computed Property syntax)
            ...state.houses[key],  // copy that specific house's properties
            points: state.houses[key].points + 3   // update its `points` property
          }
        }
      }
    

    By using the spread operator you can update only the new state leaving everything else intact.

    Example taken from this amazing article, you can find almost every possible option with great examples.

提交回复
热议问题