[说明]:代码是自己做项目的时候直接copy来的,感觉无关的可忽略
一、安装依赖包
npm i redux-persist
二、在store.js文件中配置
import { applyMiddleware, legacy_createStore as createStore, combineReducers, compose } from 'redux'
import reduxPromise from 'redux-promise'
import RightManageReducer from '../reducer/RightManageReducer'
import CollapsedReducer from '../reducer/CollapsedReducer'
import RoleListReducer from '../reducer/RoleListReducer'
import UserReducer from '../reducer/UserReducer'
//引入持久化依赖包
import { persistStore, persistReducer } from 'redux-persist'
//默认的存储引擎storage,即localStorage
import storage from 'redux-persist/lib/storage'
//持久化的配置对象,指定要持久化的Redux存储的键、存储引擎以及其他选项
const persistConfig = {
key: 'charon', //键值对key:value
storage,
blacklist: ['UserReducer','RoleListReducer','RightManageReducer'] //黑名单,设置某个reducer数据不持久化,或者可以设置白名单(whitelist)
}
//合并多个Reducer
const reducer = combineReducers({
RightManageReducer,
CollapsedReducer,
RoleListReducer,
UserReducer
})
const myPersistReducer = persistReducer(persistConfig, reducer) //将合并的reducer持久化
//合并Reducer的配置
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
//持久化后的myPersistReducer创建store
const store = createStore(myPersistReducer, composeEnhancers(applyMiddleware(reduxPromise)))
//持久器,控制Redux状态的持久化和恢复过程
const persistor = persistStore(store)
//导出
export {
store,
persistor
}
三、在入口文件中进行如下配置,index.js或App.js
import React from 'react'
import { HashRouter } from 'react-router-dom'
import IndexRouter from './router/IndexRouter'
import { Provider } from 'react-redux'
import axios from 'axios';
//导入持久化后的store和persistor
import { store, persistor } from './redux/store/store.jsx'
import { PersistGate } from 'redux-persist/integration/react'
//axios拦截器
axios.interceptors.request.use((config) => {
// 将请求的config中的localhost替换为指定的服务器地址
config.url = config.url.replace('localhost', '192.168.1.94');
return config;
});
export default function App() {
return (
// 此处需要用Provider包裹App,目的是让App所有的后代容器组件都能接收到store
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<HashRouter>
<IndexRouter></IndexRouter>
</HashRouter>
</PersistGate>
</Provider>
)
}