zoukankan      html  css  js  c++  java
  • React通过redux-persist持久化数据存储

    在React项目中,我们经常会通过redux以及react-redux来存储和管理全局数据。但是通过redux存储全局数据时,会有这么一个问题,如果用户刷新了网页,那么我们通过redux存储的全局数据就会被全部清空,比如登录信息等。

    这个时候,我们就会有全局数据持久化存储的需求。首先我们想到的就是localStorage,localStorage是没有时间限制的数据存储,我们可以通过它来实现数据的持久化存储。

    但是在我们已经使用redux来管理和存储全局数据的基础上,再去使用localStorage来读写数据,这样不仅是工作量巨大,还容易出错。那么有没有结合redux来达到持久数据存储功能的框架呢?当然,它就是redux-persist。redux-persist会将redux的store中的数据缓存到浏览器的localStorage中。

    1、对于reducer和action的处理不变,只需修改store的生成代码,修改如下

    import { createStore } from "redux";
    import reducers from "../reducers/index";
    import { persistStore, persistReducer } from "redux-persist";
    import storage from "redux-persist/lib/storage";
    import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2";
    
    const persistConfig = {
      key: "root",
      storage: storage,
      stateReconciler: autoMergeLevel2, // 查看 'Merge Process' 部分的具体情况
    };
    
    const myPersistReducer = persistReducer(persistConfig, reducers);
    
    const store = createStore(myPersistReducer);
    
    export const persistor = persistStore(store);
    export default store;

    2、在index.js中,将PersistGate标签作为网页内容的父标签

    import React from "react";
    import ReactDOM from "react-dom";
    import { Provider } from "react-redux";
    import store from "./redux/store/store";
    import { persistor } from "./redux/store/store";
    import { PersistGate } from "redux-persist/lib/integration/react";
    
    ReactDOM.render(
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          {/*网页内容*/}
        </PersistGate>
      </Provider>,
      document.getElementById("root")
    );
    

    这就完成了通过redux-persist实现React持久化本地数据存储的简单应用

    3、最后我们调试查看浏览器中的localStorage缓存数据

    发现数据已经存储到了localStorage中,此时刷新网页,redux中的数据也不会丢失

  • 相关阅读:
    html中的背景图片不能充满整个浏览器 .
    linux系统安装Memcache
    linux下如何查看某软件是否已安装
    Redis监控之redisstat安装与详解
    memcached出现:Fatal error: Call to undefined method Memcached::connect()
    PHP多进程开发与Redis结合实践
    关于大型asp.net应用系统的架构架构的选择(转载)
    浅谈https\ssl\数字证书
    利用Lucene.net对附件做搜索(转载)
    Mic's blog iis下ISAPI_Rewrite配置及 iis rewrite 规则书写
  • 原文地址:https://www.cnblogs.com/crazycode2/p/13596807.html
Copyright © 2011-2022 走看看