更新嵌套的Redux reducer对象的值

问题描述 投票:0回答:2

我有一个关于Redux的问题并更新嵌套对象的值。

让我们说这是我的初始状态:

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

当我的减速机被召唤时:

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

如何为特定ID更新loading的值?假设我用key = 2更新条目,如何用key 2将loading的值更改为true for columnState对象,并返回新状态?

javascript redux reducers
2个回答
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
           }
       }

    }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.