通常在浏览器刷新后,vuex或redux这样持续化的工具里面的数据就会丢失,之前小编发过vueX的,今天来教一下react的
1、下载
npm install redux-persist
2、配置store
这是小编的原来的index.js
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterStore";
import channelReducer from './modules/channelStore'
const store = configureStore({
reducer: {
counter: counterReducer,
channel: channelReducer
}
})
export default store
添加redux-persist
import { configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // 使用 localStorage 作为持久化存储
import userReducer from "./modules/userStore";
import channelReducer from './modules/channelStore';
import { combineReducers } from "redux";
// 定义持久化配置
const persistConfig = {
key: "root", // 本地存储的键名
storage, // 使用的存储引擎,默认为 localStorage
whitelist: ["user", "channel"] // 需要持久化的 reducer 的名字
};
// 将 reducer 与持久化配置整合
const persistedReducer = persistReducer(
persistConfig,
combineReducers({
user: userReducer,
channel: channelReducer
})
);
// 创建 Redux store
const store = configureStore({
reducer: persistedReducer // 使用整合后的 reducer
});
// 创建持久化的 store 版本
const persistor = persistStore(store);
export { store, persistor };
添加到index.js
初始
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import './global.scss'
import store from './store/index';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
修改后
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import './global.scss'
import { PersistGate } from 'redux-persist/integration/react'; // 引入 PersistGate
import { store, persistor } from './store/index';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
);