preface

When I was familiar with React, I used redux to manage the state of data globally. However, as with VUex, data was lost after refreshing, so I checked the redux-persist plugin ** on Github. ** Use redux-persist for persistent datastores.

SessionStorage or localStorage is the usual way to store data, but since we use redux to manage and store global data, using sessionStorage or localStorage feels like putting the cart before the wheel. It also adds to the workload.

Redux-persist, which works with redux to cache store data into the browser’s sessionStorage or localStorage

Redux-persist plug-in

1. Install

yarn add redux-persist --save
Copy the code

2. Import it in store.js and store it in storageSession

import {createStore,applyMiddleware} from 'redux' import thunk from 'redux-thunk' import reducer from './reducer' import  {persistStore, persistReducer} from 'redux-persist'; // Storage mechanism, Currently using sessionStorage, Can be replaced with localStorage import storageSession from 'story - persist/lib/storage/session' const persistConfig = {key: 'root', // Necessary storage:storageSession, // cache mechanism // Blacklist: ['loginStatus'] The data that is not persistent in the reducer is persistent whitelist: ['loginStatus'] const persistedReducer = persistReducer(persistConfig, reducer) export default () => { let store = createStore(persistedReducer, applyMiddleware(thunk)); let persistor = persistStore(store); return { store, persistor }; };Copy the code

3. Import file index.js and PersistGate as the parent

import React from "react";
import ReactDOM from "react-dom";
import { HashRouter } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./store/index";
import { PersistGate } from 'redux-persist/integration/react'
import { persistor } from "./store/index";
import App from "./App.js";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(  
  <HashRouter>    
    <Provider store={store}>      
      <PersistGate loading={null} persistor={persistor}>        
         <App />      
    </PersistGate>    
    </Provider>  
  </HashRouter>,  
  document.getElementById("root")
);
serviceWorker.unregister();
Copy the code

Finally, this completes redux persistence of local data stores through redux-persist.

Click the github address of the jump plugin

Click on personal blog

Thank you

  • If this article is of help to you, just click on Sunday. Thanks for reading.
  • If there are any mistakes in this article, please criticize and correct them in the comments section.
  • Image source network, if any copyright infringement please contact me to delete.