javascript - 删除 reducer 中的动态属性
问题描述
我想动态地将我想与有效负载一起删除的条目的 ID 传递到减速器中,并且我正在尝试删除一个对象属性(具有“eowvw698x”ID 的那个是动态的并且可能会更改)并保留现有的.
case DELETE_ENTRY:
return {
...state,
diaryEntries: {
...state.diaryEntries,
??????
},
};
我怎样才能做到这一点?
编辑
我使用了 Vencovsky 的回答和 Klaycon 的评论建议并写道:
case DELETE_ENTRY:
const { [payload]: dontcare, ...otherProperties } = state.diaryEntries;
return {
...state,
diaryEntries: {
...otherProperties,
},
};
其他人的解决方案改变了状态对象,这是最高算法所禁止的。
解决方案
您可以破坏state.diaryEntries
以删除该ID
const { eowvw698x, ...otherProperties } = state.diaryEntries
return {
...state,
diaryEntries: {
...otherProperties
},
};
或者
这不是最好的方法,但您可以将其设置为undefined
.
return {
...state,
diaryEntries: {
...state.diaryEntries,
eowvw698x: undefined
},
};
编辑
正如评论中所说,您正在寻找的是动态破坏一个变量,您可以在这个问题中看到如何做到这一点。
但是对于您的示例,您可以做的是破坏并命名变量,只是将其删除。
const { [keyToRemove]: anyVariableNameYouWontUse, ...otherProperties } = state.diaryEntries
return {
...state,
diaryEntries: {
...otherProperties
},
};
推荐阅读
- sql - 从一个表中选择所有列,从另一个表中选择一些列
- firebase - Firebase PWA 可以离线存储多少(多媒体文件)?
- python - 如何将坐标存储到python中的数组中?
- java - 如何解决无法启动活动错误?
- c# - EF Core 3.1 在特定数据库上下文上添加迁移
- html - CSS 问题 - 不显示/显示块显示奇怪的行为
- ios - 如何在 Swift 中按一次按钮后播放歌曲列表
- c# - 等待页面就绪硒 C# 的最佳方式
- apache-flink - 如何修复 VisualVM 中的错误“无法打开套接字文件”以分析我的应用程序的内存?
- hyperledger-fabric - 如何在 2 台机器上设置结构网络 v2?