使用 react-redux 存储数据,当页面刷新时,
store存储的数据会消失。可以考虑有两种办法
- 使用
localStorage存储数据- 优点: 简单易上手, h5 自带属性
- 缺点: 会造成数据冗余,逻辑混乱
- 使用
redux-persist(推荐)
使用教程
- 安装
redux-persist
npm install --save redux-persist
yarn add redux-persist
- 配置项
import {persistStore, persistReducer} from 'redux-persist';
// 引入机制二选一
import storage from 'redux-persist/lib/storage'; // localeStorage 机制
import storageSession from 'redux-persist/lib/storage/session // sessionStorage机制
// 黑白名单二选一
// BLACKLIST: 黑名单
const persistConfig = {
key: 'root', // key是storage的存储的key
storage: storage / storageSession, //
blacklist: ['userInfo'] // 只有 userInfo 不会被存在缓存
};
// WHITELIST: 白名单
const persistConfig = {
key: 'root',
storage: storage / storageSession,
whitelist: ['userInfo'] // 只有 userInfo 会被存在缓存
};
/**创建 reducer, 导出*/
const myPersistReducer = persistReducer(storageConfig, reducers);
const store = createStore(myPersistReducer);
export const persistor = persistStore(store);
export default store;
- 最外层文件引入
store
import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';
import Index from '@/container/index';
import store, { persistor } from './redux/store';
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Index />
</PersistGate>
</Provider>,
document.getElementById('root'),
);