[英]Set an object to Immutable Map of key value (value is an array or list) in JavaScript
[英]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.