一般来说,强烈建议不要Map使用可变对象,例如.
然而,沉浸式的魔力允许对不可变的对象进行操作,就好像它们是可变的一样。
\n具体来说,immer 使用enableMapSet支持Map 的不可变版本
\n在 redux-toolkit 中createReducer并createSlice使用 immer\'s 包装状态操作produce。
总的来说,我认为这些事实意味着这样的代码应该是安全的:
\nimport { createSlice } from \'@reduxjs/toolkit\'\n\nexport const testmapSlice = createSlice({\n name: \'testMap\',\n // Using a Map() as redux state\n initialState: new Map(),\n reducers: {\n add: (state, action) => {\n state.set(action.payload.identity, action.payload)\n },\n },\n})\nRun Code Online (Sandbox Code Playgroud)\n但是,当我在 React 组件中使用它时,我收到了礼貌的错误消息A non-serializable value was detected in the state, in the path: `testMap`. Value: Map(1)\xc2\xa0{"A" => {\xe2\x80\xa6}} …