reactjs - 更好的语法来更新 redux 上的嵌套对象
问题描述
给定一个 reducer 示例,如下所示
_({
expandAbility: (state, a: { which: string }) => ({
...state,
report: state.report && {
waitingForIt: false,
content: state.report.content && {
...state.report.content,
interaction: {
expandAbilities: !state.report.content.interaction.expandAbilities.contains(a.which)
? state.report.content.interaction.expandAbilities.add(a.which)
: state.report.content.interaction.expandAbilities.remove(a.which)
}
}
}
}),
})
(下面给出的状态类型仅用于问题上下文目的)
const initialState = {
report: undefined as
| {
waitingForIt?: boolean
content?: {
supportedFightIds: number[]
deathCut: number
reportInfo: any
deathsFull: any
deathsByPlayer: any
deathsByAbility: any
interaction: {
expandAbilities: Set<string>
}
}
}
| undefined,
error: undefined as Error | undefined
}
是否有任何技巧或“即时风味”库可以让我以expandAbility
更短的方式编写减速器更新操作?(除了可能创建一些vars
引用内部路径)
解决方案
有很多不可变的更新实用程序,请查看https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities上的一些选项,看看会发生什么成为最适合你的人。对于初学者,请查看 Immutability-helper 或 immer。
推荐阅读
- python - 无法使用 pip 安装 mysqlclient(Ubuntu 18.04 LTS)
- c# - 添加 USB 存储 Oculus GO Unity C# 的读取权限
- javascript - 仅执行特定窗口大小的代码,无需重新加载页面 jQuery 或 javascript
- powershell - 根据文件的最新修改日期检索文件的内容
- yarnpkg - 纱线热重装不是热重装
- java - 如何迭代字符串以多次提取和存储特定内容
- javascript - 如何在 CKEditor 4 中设置默认字体?
- html - CSS:在标题上包装背景颜色
- r - 所有以“CPA”R 开头的列中的 Reaplce_na
- java - 具有不同主类文件(kotlin、kotlin dsl)的项目中示例的 Gradle 任务