简体   繁体   中英

Update value of nested Redux reducer object

I have a question regarding Redux and updating a value of a nested object.

Let's say this is my initial state:

const INITIAL_STATE = {
 columnState: {
  1: {
    loading: false
  },
  2: {
    loading: false
  }
 }
};

When my reducer is called:

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state
    }
}

How do I update the value of loading for the particular id? Let's say that I update entry with key = 2, how do I change the value of loading to true for columnState object with key 2, and return the new state?

If your COLUMN_STATE_UPDATE action is updating only the columnState part (assuming type in your payload as the key):

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state,                     // keep the other keys as they were
       [type]: {                     // only update the particular one
           loading: true 
       }
    }
}

If your COLUMN_STATE_UPDATE action is updating the entire state that looks like INITIAL_STATE (again, assuming type in your payload as the key):

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state,                     // keep the other keys of state as they were
       columnState: {
           ...state.columnState,     // keep the other keys of columnState as they were
           [type]: {                 // only update the particular one
               loading: true
           }
       }

    }
}
case COLUMN_STATE_UPDATE:
// payload = {type: 1, 1: {loading: true}}
    const {type} = payload;
    return {
       columnState: {...state.columnState, [type]: payload[type] }}
};

The above could be implemented as:

/**
   * @param {Object} state The Global State Object of shape:
   * @example
   * const INITIAL_STATE = {
   *     columnState: {
   *         1: {
   *             loading: false
   *         },
   *         2: {
   *             loading: false
   *         }
   *     }
   * };
   * @param {Object} action The Action Object of shape
   * @example 
   * let action = {type: 1, 1: {loading: true}};
   * @returns {Function} The "slice reducer" function.
   */

function columnStateUpdate(state = {}, action) {
    const {type} = action;
    switch(type) {
        case COLUMN_STATE_UPDATE:   
        return {
            columnState: {...state.columnState, [type]: action[type] }}
        };
    }
}

I use action instead of payload because (state, action) is standard naming convention used in Redux Docs

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