当前位置: 首页 > 工具软件 > redux-persist > 使用案例 >

使用redux-persist解决redux数据刷新丢失问题

公良文彬
2023-12-01
  • 在React项目实际开发中,我们常常会对一些数据进行存储缓存中,防止用户刷新浏览器,数据丢失问题,比如token,用户信息之类的。之前都是手写一遍localStorage和sessionStorage储存,接来下,我们通过一个插件redux-persist配置项,来存储数据。

存储数据配置

  • 首先安装 redux-persist插件
cnpm install redux-persist
  • store文件配置
  • 本地存储 import storage from 'redux-persist/lib/storage
  • 会话存储 import storageSession from 'redux-persist/lib/storage/session
  • 其中blacklist设置哪些数据不需要存储,因为在项目中,有些数据是没有必要存储的
import { createStore,combineReducers,applyMiddleware,compose } from 'redux'

import { persistStore, persistReducer } from 'redux-persist'
import storage from "redux-persist/lib/storage"; //本地存储

import language from './language/languageReducer'

// 创建reducer对象
const allReducer = {
    language
}
// 缓存数据配置
const persistConfig = {
    key: "root",
    storage,
    whitelist: ["language"], //需要缓存的数据
    blacklist:[], //不需要缓存的数据
}
// 合并
const rootReducer  = combineReducers(allReducer)
const persistedReducer = persistReducer(persistConfig, rootReducer)
// 调试redux
const store = createStore(persistedReducer,compose(window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()))

export const persistor = persistStore(store)
export default store

使用PersistGate包装您的根组件

  • 引入插件和store配置文件
import store, {persistor} from './redux/store'

import { PersistGate } from "redux-persist/integration/react";
  • 配置
ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <App /> 
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
  • 以上就是在redux解决数据丢失问题
  • 如果想看react中英文切换,移步到 点击跳转: link.
 类似资料: