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中。

    redux-persist的使用

    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.png

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

    转自https://segmentfault.com/a/1190000018150177,作者RaoMeng

  • 相关阅读:
    c# 对文件操作
    c# 获取当前绝对路径
    c# 过滤特殊字符
    c# txt代码转换成HTML格式
    c# 对象集合转Json
    c# DataReader转换为Json
    c# DataSet转换为Json
    ABAP-SAP的LUW和DB的LUW的区别
    ABAP-关于隐式与显式的DB Commit
    ABAP-Keyword Documentation
  • 原文地址:https://www.cnblogs.com/GeniusZ/p/12398253.html
Copyright © 2011-2022 走看看