簡體   English   中英

在不可變的 Map 中設置而不覆蓋先前的值

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

我正在調度一個動作,該動作在地圖內的狀態中設置一個人的 id。 我在減速器中的代碼是這樣的:

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而不是 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