更新嵌套Redux reducer对象的值

时间:2019-02-20 17:23:44

标签: javascript redux reducers

我对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并返回新状态?

2 个答案:

答案 0 :(得分:1)

如果您的COLUMN_STATE_UPDATE操作仅更新了columnState部分 (假设您的type中的payload为密钥)

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的整个状态(同样,以您type中的payload为键):

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

    }
}

答案 1 :(得分:0)

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中使用的标准命名约定