温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React通过redux-persist持久化数据存储的方法示例

发布时间:2020-10-09 21:10:07 来源:脚本之家 阅读:306 作者:RaoMeng 栏目:web开发

在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缓存数据

React通过redux-persist持久化数据存储的方法示例

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI