在不可变 Map 中设置而不覆盖先前的值

Set in immutable Map without override the previous value

我正在调度一个动作,该动作在地图内的状态中设置一个人的 ID。我在reducer中的代码是这样的:

const customerSessionReducer = (customerSession = Map(), action) => {
  if (!action) {
    return customerSession;
  }
  switch (action.type) {
    case SET_CUSTOMER_SESSION:
      return customerSession
        .set('customerSession', action.payload.customerID);
    default:
      return Map();
  }
};

当我调度操作时,状态的 customerSessionPart 会更新,但不会保留先前的值。我想以某种方式创建一个 Map,其键包含 customerID。我不想丢失以前的客户 ID 您知道如何实现这一目标吗? 例如,假设我第一次发送一个动作,我的 customersession 有 customerId。当我再次派遣时,我的地图不像 {customerID, customerID} 但它正在丢失以前的值

调用 map.set(key, value) 将替换提供的值 key,您有几个选择:

有一个列表作为您要替换的值

const previousList = customerSession.get('customerSession');
 //...

 case SET_CUSTOMER_SESSION:
    return customerSession
      .set('customerSession', previousList.push(action.payload.customerID));

使用 customerID 作为 Map

上的键
case SET_CUSTOMER_SESSION:
    return customerSession
      .set(action.payload.customerID, 'some-other-value?');

如果您不需要存储任何其他值并且希望在您的商店中拥有唯一值,请使用 Set 而不是地图

const customerSessionReducer = (customerSession = Set(), action) => {
  if (!action) {
    return customerSession;
  }

  switch (action.type) {
    case SET_CUSTOMER_SESSION:
      return customerSession
        .add(action.payload.customerID);
    default:
      return Set();
  }
};