React-redux is used to store data. When the page is refreshed, the data stored in the Store disappears. Two approaches can be considered

  • uselocalStorageStore the data
    • Advantages: Easy to use, H5 comes with its own attributes
    • Disadvantages: May cause data redundancy, logic confusion
  • useredux-persist(recommended)

Using the tutorial

  1. The installationredux-persist
npm install --save redux-persist
yarn add redux-persist
Copy the code
  1. Configuration items
import {persistStore, persistReducer} from 'redux-persist';
// Choose between two mechanisms
import storage from 'redux-persist/lib/storage'; / / localeStorage mechanism
import storageSession from 'story - persist/lib/storage/session / / / / sessionStorage mechanism of black and white list a choice / / BLACKLIST: BLACKLIST const persistConfig = {key:'root', // key是storage的存储的key
  storage: storage / storageSession, // 
  blacklist: ['userInfo'// only userInfo will not be cached}; // WHITELIST: const persistConfig = {key: 'root', storage: storage / storageSession, whitelist: ['userInfo'] // only userInfo will be cached}; / / myPersistreducers = Persistreducers (storageConfig, reducers); const store = createStore(myPersistReducer); export const persistor = persistStore(store); export default store;Copy the code
  1. Outermost file is importedstore
import React from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';

import Index from '@/container/index';
import store, { persistor } from './redux/store';

ReactDOM.render(
	<Provider store={store}>
		<PersistGate loading={null} persistor={persistor}>
				<Index />
		</PersistGate>
	</Provider>.document.getElementById('root'));Copy the code