[React] redux-persist of redux persistence

redux-persist installation

//Installation command, after installation, check whether package.json is installed on
yarn add redux-persist --save

import {
    
     createStore,combineReducers } from "redux";
//配置数据的持久化效果
import {
    
    persistStore,persistReducer} from "redux-persist"
//导入需要配置的数据源,可以选择,storage,cookie,session等
import storage from "redux-persist/lib/storage";

...  //重复代码省略
//可以合并多个模块
const Reducer = combineReducers({
    
    
    ....
})

//定义配置的信息
const persitConfig = {
    
    
    key:"root",
    storage:storage,
   // 如果不想将部分state持久化,可以将其放入黑名单(blacklist)中.黑名单是设置
  blacklist: ['不想缓存的状态的名字']
}
//创建持久化的配置persist的信息
const persist_reducers = persistReducer(persitConfig,Reducer);
//创建存储对象并且抛出对象
const store = createStore(persist_reducers);
const persistor =  persistStore(store);//使用persistStore包裹一下
//抛出store和持久化工具两个对象信息
export {
    
    store,persistor};
  • Configured in the index.js entry file

Wrap the root component with PersistGate in the entry file. This will delay the rendering of the app view until the persistent state is retrieved and saved in redux.
Import the corresponding thrown store object and persistor object and use the configuration directly

import {
    
     store, persistor } from "./store";//redux中的数据获取对象信息
//如果使用React,则使用 PersistGate 包裹根组建
import {
    
     PersistGate } from 'redux-persist/lib/integration/react';
//导入react-redux对象
import {
    
     Provider } from "react-redux"

root.render(
    <Provider store={
    
    store}>
        {
    
    /* // loading 和 persistor是2个必需属性 */}
        {
    
    /* // loading={null} || loading={<LoadingView />} LoadingView为React组件 */}
        {
    
    /* // 最好将loading={null},写成loading={<LoadingView />} 报错,原因暂不明 */}
        <PersistGate loading={
    
    null} persistor={
    
    persistor}>
            <Routes />
        </PersistGate>
    </Provider>
)

Guess you like

Origin blog.csdn.net/weixin_50636536/article/details/128378696