Redux Toolkit和Redux persist不可序列化错误

vjhs03f7  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(141)

我不明白为什么即使我的UserDataState只包含普通的js对象也会触发这个错误。我读到过禁用序列化检查可能是一个选项,但对我来说似乎不正确。
在路径中的操作中检测到不可序列化的值:register.数值:function register(key)看一下分派此操作的逻辑:对象{ type:“persist/PERSIST”,注册:register(key),rehydrate:rehydrate(key,payload,err)}
(See https://redux.js.org/faq/actions#why-should-type-be-a-string. t-least-serializable-why-should-my-action-types-be-constants)(要允许不可序列化的值,请参阅:https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)
UserSlice.ts

interface UserDataState {
  userData: {
    id: string | null;
    createdAt: string | null;
    updatedAt: string | null;
    email: string | null;
    firstName: string | null;
    lastName: string | null;
    username: string | null;
    profilePicture: string | null;
    gamesPlayed: number | null;
    gamesWon: number | null;
    userPoints: number | null;
    userLevel: number | null;
    isOnline: boolean | null;
    currentRoom: string | null;
  }
}

Store.ts

const appReducer = combineReducers({
  channels: ChannelSlice,
  user: persistReducer({ key: "user", storage }, userReducer),
})

const rootReducer: Reducer = (state: RootState, action: AnyAction) => {
  if (action.type === "user/unsetUser") {
    storage.removeItem('persist:user')

    return appReducer(undefined, action)
  }
  return appReducer(state, action)
}

export const store = configureStore({
  reducer: rootReducer,
})

以下是我在redux中的原始数据:

{
  channels: {
    activeChannel: null,
    visibleChannels: []
  },
  user: {
    userData: {
      id: null,
      createdAt: null,
      updatedAt: null,
      email: null,
      firstName: null,
      lastName: null,
      username: null,
      profilePicture: null,
      gamesPlayed: null,
      gamesWon: null,
      userPoints: null,
      userLevel: null,
      isOnline: null,
      currentRoom: null
    },
    _persist: {
      version: -1,
      rehydrated: true
    }
  }
}
vzgqcmou

vzgqcmou1#

您不想 * 完全 * 关闭可序列化检查,但您希望忽略一些使用不可序列化有效负载的特定操作。
请参阅Redux-Persists和Serializability Middleware文档了解完整的细节。
范例:

import { configureStore } from '@reduxjs/toolkit';
import {
  ...,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist';

const reduxPersistActions = [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER];

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [...reduxPersistActions],
      },
    }),
});

相关问题