给出如下所示的 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
}
是否有任何技巧或“当下 flavor ”库可以让我以更短的方式编写像 expandAbility
这样的 reducer 更新操作? (除了可能创建一些vars
来引用内部路径)
最佳答案
有很多不可变的更新实用程序,请在https://github.com/markerikson/redux-ecosystem-links/blob/master/immutable-data.md#immutable-update-utilities查看一些选项。看看什么最适合您。 对于初学者来说,请查看 Immutability-helper 或 immer。
关于reactjs - 更好的语法来更新 redux 上的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50360531/