在使用redux中发现,当我们刷新页面之后,store中的状态会消失。但是在某些时候可能不仅需要用到sotre来管理各种状态,还需要store里的数据能一直保存,就像缓存一样。redux-persist可以让你的数据从state分离出来,保存到浏览器缓存中,以便实现数据的持久化存储
一、下载依赖
npm install redux-persist--save
二、然后修改store的入口文件
import {createStore, applyMiddleware} from 'redux' import mainReducers from "./reduces"; import thunk from "redux-thunk"; 引入我们需要的方法 import {persistStore, persistReducer} from 'redux-persist' import storage from 'redux-persist/lib/storage' const persistConfig = { key: 'root', storage: storage, } persistConfig 对象还可以设置黑名单白名单,就是不需要永久保存的数据。 const myPersistReducer = persistReducer(persistConfig, mainReducers) const store = createStore(myPersistReducer, applyMiddleware(thunk)) export const persistor = persistStore(store) export default store
三、最后在react的入口文件中设置如下
// import api from './api' import React, { Component } from 'react' import { BrowserRouter, Route, Redirect } from 'react-router-dom' import { Provider } from "react-redux"; //引入PersistGate标签,和persistor import { PersistGate } from "redux-persist/lib/integration/react"; import store from "./store/index"; import { persistor } from "./store"; import routes from './Router' import requireLogin from './requireLogin' import Login from './pages/admin/login' class App extends Component { render() { return ( <Provider store={store}> <BrowserRouter> <PersistGate loading={null} persistor={persistor}> <div> <Route exact path="/" render={() => <Redirect to="/web/index" push />} /> <Route path='/login' component={Login} /> {routes.map((route, i) => ( <Route key={i} path={route.path} component={ route.path.includes('/admin') ? requireLogin(route.component) : route.component } /> ))} </div> </PersistGate> </BrowserRouter> </Provider> ); } } export default App;