我正在用reactjs开发一个应用程序,并使用redux作为我的状态管理工具。
我想使用redux-persistent来持久化我从服务器获取的数据
但是我收到这个错误
Uncaught Error: config is required for persistReducer
at persistReducer (persistReducer.js:25:1)
at redux.js:468:1
我的代码
import { configureStore, combineReducers } from '@reduxjs/toolkit'
import userReducer from './UserSlice'
import storage from 'redux-persist/lib/storage'
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from 'redux-persist'
const rootReducer = combineReducers({user: userReducer})
这就是我创建持久配置的地方
const persistConfigs = {
key: 'root',
version: 1,
storage,
}
这是我使用持久配置的地方
const persistedReducer = persistReducer(persistConfigs, rootReducer)
export const store = configureStore({
reducer: {
reducer: persistReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
},
})
export const persistor = persistStore(store)
UserReducer
This is the userSlice that I imported in store.js, the userSlice update the state when the user logs into the system.
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
currentUser: null,
loading: false,
error: false
}
它有三种状态:用户点击提交按钮时的启动状态,用户成功登录时的成功状态,以及登录失败时的失败状态
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
loginStart: (state) => {
state.loading = true;
},
loginSuccess: (state, action) => {
state.loading = false;
state.currentUser = action.payload;
},
loginFail: (state) => {
state.loading = false;
state.error = true;
},
logout: (state) => {
state.loading = false;
state.error = false;
state.currentUser = null;
}
},
})
export const {loginStart, loginSuccess, loginFail, logout} = userSlice.actions
export default userSlice.reducer;
链接到沙箱
https://codesandbox.io/s/wizardly-wing-jsv617
应该使用persistedReducer
作为减速器,而不是persistReducer
const persistedReducer = persistReducer(persistConfigs, rootReducer)
export const store = configureStore({
reducer: {
reducer: persistedReducer,