赞
踩
最近在使用react的时候有用到redux,对数据进行全局的状态管理,但是发现和vuex一样会出现刷新之后数据丢失的问题,于是在github上面查阅了 redux-persist 插件,使用redux-persist进行持久化数据存储 。
通常我们会使用sessionStorage或者localStorage来进行数据存储,但既然我们使用了redux来管理和存储全局数据,此时再使用sessionStorage或者localStorage存储,感觉会本末倒置,而且还增加了工作量。
这个时候 **redux-persist,**满足你的需求,它结合redux将store中的数据缓存到浏览器的sessionStorage或者localStorage中
yarn add redux-persist --save
- /*
- * @Author: chengxinyu
- * @Date: 2021-12-03 18:28:29
- * @LastEditors: chengxinyu
- * @LastEditTime: 2021-12-10 17:27:13
- */
-
- import { createStore } from 'redux';
- import reducer from './reducer';
- import { persistStore, persistReducer } from 'redux-persist';
- // 存储机制,可换成其他机制,当前使用sessionStorage机制
- import storageSession from 'redux-persist/lib/storage/session';
- // import storage from 'redux-persist/lib/storage'; //localStorage机制
- //import { AsyncStorage } from 'react-native'; //react-native
- // 数据对象
- const storageConfig = {
- key: 'root', // 必须有的
- storage: storageSession, // 缓存机制
- blacklist: [], // reducer 里不持久化的数据,除此外均为持久化数据
- };
-
- const myPersistReducer = persistReducer(storageConfig, reducer);
- const store = createStore(myPersistReducer);
- export const persistor = persistStore(store);
- export default store;
-
- // const configureStore = () => createStore(reducer);
- // export default configureStore;
- /*
- * @Author: chengxinyu
- * @Date: 2021-11-24 10:34:44
- * @LastEditors: chengxinyu
- * @LastEditTime: 2021-12-08 09:13:11
- */
-
- import React, { useState, useEffect } from 'react';
- import { Menu, HomeHeader } from '@/components';
- import './index.less';
- // 状态
- // import store from '@/store/index';
- import { useLocation } from 'umi';
- import { Provider } from 'react-redux';
- import store from '../store/index';
- import { PersistGate } from 'redux-persist/lib/integration/react';
- import configStore from '../store/index';
- import { persistor } from '../store/index';
- // 页面刷新本地仓库数据不消失
-
- function BasicLayout(props) {
- const location = useLocation();
- const paths = ['/login'];
-
- return (
- <Provider store={store}>
- <PersistGate loading={null} persistor={persistor}>
- <div className="lay">
- <div className="left_container">
- <Menu
- show={paths.includes(location.pathname)}
- pathname={location.pathname}
- ></Menu>
- </div>
-
- <div className="right_container">
- <HomeHeader
- show={paths.includes(location.pathname)}
- pathname={location.pathname}
- ></HomeHeader>
- {props.children}
- </div>
- </div>
- </PersistGate>
- </Provider>
- );
- }
-
- export default BasicLayout;
最后,这样就完成了通过redux-persist实现redux持久化本地数据存储。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。