redux-persist 配置

在reduxjs/toolkit基础上进行更改,主要作用为store数据持久化

在reduxjs/toolkit的基础上,新增一下内容,将原先configureStore中的reducer值更换即可

1、下载

npm i redux-persist -D

2、store文件改造

新增内容如下:

import { persistStore, persistReducer } from "redux-persist";
import storage from 'redux-persist/lib/storage';
const persitConfig = {
    key:"root",
    storage
}
const persistedReducer = persistReducer(
    persitConfig,
    combineReducers({
        userSlice,mySlice
    })
)
const persistor = persistStore(store);
export {store,persistor}

修改内容:

const store = configureStore({
    reducer: persistedReducer,
    middleware:getDefaultMiddleware => getDefaultMiddleware({
        //关闭redux序列化检测, 异步函数请求接口时,返回的对象无法序列化
        serializableCheck:false
    })

})

最终代码:

import { combineReducers, configureStore } from '@reduxjs/toolkit'
import { persistStore, persistReducer } from "redux-persist";
import storage from 'redux-persist/lib/storage';
import userSlice from './slice/userSlice';
import mySlice from './slice/mySlice';
const persitConfig = {
    key:"root",
    storage
}
const persistedReducer = persistReducer(
    persitConfig,
    combineReducers({
        userSlice,mySlice
    })
)
const store = configureStore({
    reducer: persistedReducer,
    middleware:getDefaultMiddleware => getDefaultMiddleware({
        //关闭redux序列化检测, 异步函数请求接口时,返回的对象无法序列化
        serializableCheck:false
    })

})
const persistor = persistStore(store);

// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

export {store,persistor}

你可能感兴趣的:(react.js,store持久化,reduxjs/toolkit)