赞
踩
前端数据需要存在本地,来避免多次请求,提高前端效率。可以选的有cookie,localstorage,localsession各中区别,主要的就是大小限制等
比如登录信息,管理系统的权限,菜单列表等,还是选择存localstorage/localsession吧。在每次请求到数据后都去调用一次localstorage.set()感觉也挺麻烦的,最好的就是redux里有了数据就直接自动放入localstorage里,于是用redux-persist
npm install redux-persist --save
.babelrc 配置按需加载
"plugins": [
"transform-runtime",
["import", { "libraryName": "redux-persist", "libraryDirectory": "es"}, "redux-persist"]
],
包装createReducer或者rootReducer
import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware, { END } from 'redux-saga'; // 返回的是combineReducers import createReducer from '../reducers/index'; import { persistReducer } from 'redux-persist'; import storage from 'redux-persist/es/storage' const sagamiddleware = createSagaMiddleware(); // 数据对象 const storageConfig = { key: 'root', // 必须有的 storage, // storage is now required blacklist: [] // reducer 里不持久化的数据 } export default function configureStore(initStore = {}) { const middlewares = [sagamiddleware]; const createStoreMiddleware = applyMiddleware(...middlewares)(createStore); const store = createStoreMiddleware( // 包装createReducer 即 rootReducer persistReducer(storageConfig, createReducer()), initStore ); store.runSaga = sagamiddleware.run; store.close = () => store.dispatch(END); // 热重载 if (module.hot) { module.hot.accept(() => { const nextRootReducer = require('../reducers/index').default; store.replaceReducer(persistReducer(storageConfig, createReducer(nextRootReducer))) }, ) } return store }
再到app.js 入口文件中,利用PersistGate包裹根组建
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import rootSaga from './sagas/index'; import { persistStore } from 'redux-persist'; import { PersistGate } from 'redux-persist/es/integration/react'; import configureStore from "./store/configureStore"; import RootRoute from './router/rootRoute'; // 所有定义好的路由 const store = configureStore(); const persistor = persistStore(store); store.runSaga(rootSaga); const Loading = () => <div>loading</div>; ReactDOM.render( <Provider store = {store} > <PersistGate loading={<Loading/>} persistor={persistor}> <RootRoute/> </PersistGate> </Provider>, document.getElementById('root') );
登录后返回信息保存到localstorage里
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。