redux-persist 配置

直接复制以下完整代码,修改combineReducers中的slice即可

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,
    //whitelist:['白名单模块'], 用来配置是否缓存
}
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<typeof store.getState>
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

export {store,persistor}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值