欢迎关注微信公众号:【 全栈攻略 】

vuex有数据持久化插件,redux有没有呢?答案是肯定的。那就是简单易用的redux-persist官网链接

两步走起!

一,配置我们创建store的文件

store/index.js

import { createStore, applyMiddleware, compose } from 'redux';
import reducers from './reducers';
import thunk from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
// 存储对象,默认存储到localstorage
const persistConfig = {
  key: 'root',
  storage,
}
// 重新组装reducer
const persistedReducer = persistReducer(persistConfig, reducers)
// redux调试工具配置代码
const composeEnhancers =
  typeof window === 'object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;

const enhancer = composeEnhancers(
  applyMiddleware(thunk),
);
// 创建store
const store = createStore(persistedReducer, enhancer);
// 应用redux-persist以完成数据持久化
export const persistor = persistStore(store)

export default store;

二,store持久化的应用

入口文件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store/index';
import { PersistGate } from 'redux-persist/integration/react';
import { persistor } from './store/index';
import 'antd/dist/antd.css';
import './assets/css/index.scss';
import './assets/icon/iconfont.css';
import App from './App';

ReactDOM.render(
	// antd 国际化配置
 <Provider store={store} >
 	// 持久化store配置 把App根组件以及所有子组件包裹起来
   <PersistGate loading={null} persistor={persistor}>
        <App />
   </PersistGate>
</Provider>, 
document.getElementById('root'));
    

至此,两步搞定,这时我们F12,就可以看到如下:
在这里插入图片描述
成功存储在localstorage中!

PS:未来的你,一定会感谢今天拼命努力的自己!
Logo

前往低代码交流专区

更多推荐