gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:06:10 26 4
gpt4 key购买 nike

我正在调度一个 Action ,该 Action 在 map 内的状态中设置一个人的 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您知道如何实现这一目标吗?例如,假设我第一次发送一个 Action ,我的 customersession 有 customerId。当我再次调度时,我的 map 不像 {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();
}
};

关于javascript - 在不可变 Map 中设置而不覆盖先前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com