在Redux Toolkit中更新reducer内的状态的正确方式

huangapple go评论67阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月21日 15:36:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定