英文:
Correct way to update state inside reducer in redux toolkit
问题
这是正确的方法吗?因为根据 Immer 的规则,我们要么修改状态,要么返回一个新的对象,但在这段代码中,只改变了引用。
我只想知道这样做是否正确?
英文:
`
import { createSlice } from "@reduxjs/toolkit"
const initialState = {
getAllCountries: null,
getAllStatesByCountry: null,
getAllCitiesByState: null
}
export const locationSlice = createSlice({
name: 'location',
initialState: initialState,
reducers: {
getAllCountries: (state, action) => {
state.getAllCountries = action.payload.data
},
getAllStatesByCountry: (state, action) => {
state.getAllStatesByCountry = action.payload.data
},
getAllCitiesByState: (state, action) => {
state.getAllCitiesByState = action.payload.data
}
}
});
export const {
getAllCountries,
getAllStatesByCountry,
getAllCitiesByState
} = locationSlice.actions;
`
Is it the correct way to update state inside reducer. Because according to immer, we either mutate the state or return a new object, but in this code, only the reference is being changed.
I just wanted to know if this is the correct way?
答案1
得分: 0
你没有改变引用 state
,但你修改了对象 state
。这是完全可以的。
// 这修改了 `state`。这是可以的
state.foo = bar
// 这重新分配 `state`/改变了引用。这不支持!
state = bar
// 这返回一个新的对象。这也是可以的
return bar
要了解更多信息,请查看Redux Toolkit文档中关于使用immer
编写reducers的内容:在Redux Toolkit文档中编写reducers。
英文:
You are not changing the reference state
, but you are modifying the object state
. It's perfectly fine.
// this modifies `state`. this is good
state.foo = bar
// this reassigns `state`/changes the reference. this is not supported!
state = bar
// this returns a new object. this is also good
return bar
For more information see writing reducers with immer
in the Redux Toolkit documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论