redux之redux-persist数据持久化

原因:redux和其它状态管理技术一样,刷新页面后,数据就会恢复成初始状态。

所以:redux-persist会将redux的store中的数据自动缓存到浏览器的 localStorage 中,不再需要单独去存储了

仓库地址: https://github.com/rt2zz/redux-persisticon-default.png?t=N0U7https://github.com/rt2zz/redux-persist1,安装依赖 

npm i redux-persist

2,在store.js中配置

import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // 默认在localStorage
// 配置持久化
const persistConfig = {
    key: 'root',
    storage,
    whitelist:['switchCity'] ///设置某个reducer数据持久化,
    // blacklist:[]  //设置某个reducer数据不持久化,
  }
const persistedReducer = persistReducer(persistConfig, reducers)

// applyMiddleware添加一个中间件
let store = createStore(persistedReducer,applyMiddleware(reduxThunk,reduxPromise))
let persistor = persistStore(store)
export {store,persistor} 

在根目录index.js中

import { store,persistor } from './pages/cinema_react_redux/redux/store'
import { PersistGate } from 'redux-persist/integration/react'
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>

运行效果图

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Redux Toolkit的数据持久,你可以使用一些库或中间件来帮助你完成这个任务。下面是一种常用的方法: 1. 使用redux-persist库:redux-persist是一个用于在Redux中实现数据持久的库。它提供了一个简单的方法来将Redux状态保存到本地存储(如LocalStorage或AsyncStorage)中,并在应用程序重新加载时还原状态。 首先,安装redux-persist库: ``` npm install redux-persist ``` 然后,在你的Redux store配置中,使用`persistStore`函数来创建持久的store: ```javascript import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // 默认使用LocalStorage import rootReducer from './reducers'; const persistConfig = { key: 'root', storage, }; const persistedReducer = persistReducer(persistConfig, rootReducer); export const store = configureStore({ reducer: persistedReducer, }); export const persistor = persistStore(store); ``` 这里,`persistConfig`对象用于配置持久设置。你可以指定一个键(key)和存储引擎(storage),它默认使用LocalStorage。然后,使用`persistReducer`函数将根reducer与配置一起包装,创建一个持久的reducer。 最后,通过调用`persistStore`函数来创建一个持久的store,并导出store和persistor。 2. 在根组件中使用`PersistGate`组件:`PersistGate`是redux-persist提供的一个React组件,用于在应用程序加载时等待持久恢复完成。在根组件中使用`PersistGate`包裹你的应用程序组件,并传入`persistor`作为prop。 ```javascript import { PersistGate } from 'redux-persist/integration/react'; import { persistor } from './store'; ReactDOM.render( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <App /> </PersistGate> </Provider>, document.getElementById('root') ); ``` 这样,当你的应用程序重新加载时,Redux状态将从本地存储中恢复。 请注意,这只是一种实现Redux Toolkit数据持久的方法之一,你也可以使用其他类似的库或中间件来实现类似的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值