是否可以在 slice reducer 中重新分配整个状态(使用 Redux ToolKit)?
Is it possible to reassign the whole state in a slice reducer (using Redux ToolKit)?
我正在使用 Redux Toolkit 的 createSlice()
。
并尝试创建一个 reducer,将来自外部源的数据填充到 redux 状态。
我正在尝试通过在操作负载中传递一个对象来更新整个状态:
.
reducers: {
populateData: (state, action) => {
state = action.payload
}
.
但只有当我为每个对象键创建一个缩减器时它才会起作用。
有没有办法一次完成所有这些?
这是一个常见的误解,实际上我昨天刚刚写了一个新的 "Writing Reducers with Immer" docs page 来回答这个问题。引用:
A common mistake is to try assigning state = someValue directly
. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.
相反,您需要:return action.payload
,这将完全替换现有状态。
我正在使用 Redux Toolkit 的 createSlice()
。
并尝试创建一个 reducer,将来自外部源的数据填充到 redux 状态。
我正在尝试通过在操作负载中传递一个对象来更新整个状态:
.
reducers: {
populateData: (state, action) => {
state = action.payload
}
.
但只有当我为每个对象键创建一个缩减器时它才会起作用。 有没有办法一次完成所有这些?
这是一个常见的误解,实际上我昨天刚刚写了一个新的 "Writing Reducers with Immer" docs page 来回答这个问题。引用:
A common mistake is to try assigning
state = someValue directly
. This will not work! This only points the local state variable to a different reference. That is neither mutating the existing state object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.
相反,您需要:return action.payload
,这将完全替换现有状态。