一般来说,使用可变对象,例如Map
is 强烈劝阻 https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state.
然而,神奇的immer https://github.com/immerjs/immer允许对不可变对象进行操作,就像它们是可变的一样。
具体来说,immer 支持使用 Map 的不可变版本启用地图集 https://immerjs.github.io/immer/docs/map-set
在 redux 工具包中createReducer
and createSlice
用 immer 包装状态操作produce
.
总的来说,我认为这些事实意味着这样的代码应该是安全的:
import { createSlice } from '@reduxjs/toolkit'
export const testmapSlice = createSlice({
name: 'testMap',
// Using a Map() as redux state
initialState: new Map(),
reducers: {
add: (state, action) => {
state.set(action.payload.identity, action.payload)
},
},
})
但是,当我在 React 组件中使用它时,我收到礼貌的错误消息A non-serializable value was detected in the state, in the path: `testMap`. Value: Map(1) {"A" => {…}} Take a look at the reducer(s) handling this action type: testMap/add.
.
有没有办法安全使用Map
没有收到此错误消息?