【发布时间】:2020-11-12 04:35:24
【问题描述】:
一般来说,使用可变对象如Map就是strongly discouraged。
然而,immer 的魔力允许不可变对象像可变对象一样被操作。
具体来说,immer 支持使用 enableMapSet 的不可变版本的 Map
在 redux-toolkit createReducer 和 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 而不会收到此错误消息?
【问题讨论】:
标签: redux redux-toolkit immer.js