赞
踩
在我们使用项目的时候会用到redux来进行缓存机制,但是刷新页面之后store 就丢失或者重置
redux的store状态数据不是永久保存的,state只是一个内存机制。
解决办法
使用浏览器内部存储的方式进行存储在cookie,localStorage,sessionStorage 使用的时候直接获取就好
在react中可以使用redux-persist包,将store保存在浏览器的sessionStorage或者localStorage中。
1.redux-persist可以让你的数据从state分离出来,保存到浏览器缓存中,以便实现数据的持久化存储
import {persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import {PersistGate} from 'redux-persist/integration/react';
2.使用Provider,通过redux-persist重新构造store
const myReducer = persistReducer({
key: 'root',
storage
}, rootReducer);
const store = createStore(myReducer);
3.然后在Provider内部包装一个PersistGate组件即可。
const persistor = persistStore(store);
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Router>
<Routes/>
</Router>
</PersistGate>
</Provider>,
document.getElementById('root')
);
4.完整代码如下:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router} from 'react-router-dom';
import {createStore, combineReducers} from 'redux';
import {Provider} from 'react-redux';
import Routes from './Routes';
import './assets/styles/common.css';
// persist store
import {persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import {PersistGate} from 'redux-persist/integration/react';
// 引入子reducer文件
import InfoAreaReducer from './pages/Login/components/InfoArea/InfoAreaReducer';
const rootReducer = combineReducers({
InfoAreaReducer
});
const myReducer = persistReducer({
key: 'root',
storage
}, rootReducer);
const store = createStore(myReducer);
const persistor = persistStore(store);
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Router>
<Routes/>
</Router>
</PersistGate>
</Provider>,
document.getElementById('root')
);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。