Solve react store page refresh is reset problem

When WEB SPA project development, use redux, if the jump page, you will find redux will be reset when, after the jump, which is
that we do not want to see it is necessary to solve this problem.
Since the store is memory drive, rather than caching mechanism. Therefore, refresh the page (jump) store will be initialized when the refresh is necessary to store data persistence.

Solve redux in the event of the page jump will be reset problem

Use redux-persistpackage, store or save sessionStorage localStorage browser.

Use as follows:

  1. Introducing package redux-persisit
import {persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import {PersistGate} from 'redux-persist/integration/react';
  1. Use Provider, by redux-persistreconstructing store
const myReducer = persistReducer({
    key: 'root',
    storage
}, rootReducer);
const store = createStore(myReducer);
  1. Then Provider within a package PersistGateassembly can.
const persistor = persistStore(store);
ReactDOM.render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <Router>
                <Routes/>
            </Router>
        </PersistGate>
    </Provider>,
    document.getElementById('root')
);

The complete code is as follows

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')
);


Guess you like

Origin blog.csdn.net/wang19970228/article/details/95221856