更新嵌套 Redux reducer 对象的值

Update value of nested Redux reducer object

我对 Redux 和更新嵌套对象的值有疑问。

假设这是我的初始状态:

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

当我的减速器被调用时:

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

如何更新特定 ID 的 loading 值? 假设我使用键 = 2 更新条目,对于键为 2 的 columnState 对象,如何将 loading 的值更改为 true,以及 return 新状态?

如果您的 COLUMN_STATE_UPDATE 操作仅更新 columnState 部分 (假设你的 payload 中的 type 作为键):

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

如果您的 COLUMN_STATE_UPDATE 操作正在更新看起来像 INITIAL_STATE 的整个状态(同样,假设 payload 中的 type 作为键):

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] }}
};

以上可以实现为:

/**
   * @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] }}
        };
    }
}

我使用 action 而不是 payload 因为 (state, action)Redux Docs

中使用的标准命名约定