[英]How to properly delete object subfields when dispatching a new redux action?
I'm wondering what is the right way to delete a nested field in redux actions.我想知道在 redux 操作中删除嵌套字段的正确方法是什么。 For example, I have this code:
例如,我有这段代码:
const SUBSCRIBE = 'SUBSCRIBE';
const UNSUBSCRIBE = 'UNSUBSCRIBE';
export default function reducer(state = {}, action) {
const {
productName,
products,
componentName
} = action;
switch (action.type) {
case UNSUBSCRIBE: {
if (state[productName]?.[componentName]) {
const newState = { ...state };
delete newState[productName][componentName];
return newState;
} else {
return state;
}
}
default:
return state;
}
}
export function unsubscribe(productName, componentName) {
return {
type: UNSUBSCRIBE,
productName,
componentName
};
}
In UNSUBSCRIBE
action I delete newState[productName][componentName]
field, however this will also delete the field on the "old" state. So theoretically if there're other actions which use this field it may be lost for them because the state is mutated.在
UNSUBSCRIBE
操作中,我删除了newState[productName][componentName]
字段,但是这也将删除“旧”state 上的字段。因此理论上,如果有其他操作使用此字段,它可能会丢失,因为 state 是变异了。 Should I deep copy old state into newState
and then delete newState[productName][componentName]
?我应该将旧的 state 深复制到
newState
中,然后删除newState[productName][componentName]
吗?
You can do one of two:您可以执行以下两项之一:
productName
state and delete componentName
from that copyproductName
state 的副本并从该副本中删除componentName
if (state[productName]?.[componentName]) {
const newProductState = { ...state[productName] };
delete newProductState[componentName];
return {
...state,
[productName]: newProductState
};
} else {
return state;
}
componentName
as undefined (which I would personaly prefer to do)componentName
标记为未定义(我个人更愿意这样做)if (state[productName]?.[componentName]) {
return {
...state,
[productName]: {
...state[productName],
[componentName]: undefined,
},
};
} else {
return state;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.