繁体   English   中英

更新嵌套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 ,并返回新状态?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM