简体   繁体   English

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

[英]Set in immutable Map without override the previous value

i'm dispatching an action which sets in the state inside a map an id for a person.我正在调度一个动作,该动作在地图内的状态中设置一个人的 id。 My code in the reducer is like this:我在减速器中的代码是这样的:

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();
  }
};

When i'm dispatching the action the customerSessionPart of the state is updated without holding the previous value.当我分派动作时,状态的 customerSessionPart 会在不保留先前值的情况下更新。 I want somehow create a Map whose keys contains the customerIDs.我想以某种方式创建一个 Map,其键包含 customerID。 I don't want to lose the previous customerIDs Do you have any idea of how to achieve this?我不想丢失以前的客户 ID 你知道如何实现这一点吗? For example suppose i dispatch an action for the first time, My customersession has the customerId.例如,假设我第一次分派一个动作,我的 customersession 有 customerId。 When i'm dispatching again my Map is not like {customerID, customerID} but it is lossing the previous value当我再次调度时,我的地图与 {customerID, customerID} 不同,但它丢失了以前的值

calling map.set(key, value) will replace the value on the provided key , you have a couple of options:调用map.set(key, value)将替换提供的key上的值,您有几个选项:

have a list as the value you are replacing有一个列表作为您要替换的值

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

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

use the customerID as the key on that Map使用 customerID 作为该Map上的键

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

if you don't need to store any other value and you want to have unique values in your store, use a Set instead of a map如果您不需要存储任何其他值并且希望在您的商店中拥有唯一值,请使用Set而不是 map

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();
  }
};

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

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