1. 程式人生 > >react中redux利用redux-persist資料持久化

react中redux利用redux-persist資料持久化

前端資料需要存在本地,來避免多次請求,提高前端效率。可以選的有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裡
在這裡插入圖片描述