首页 > 解决方案 > 在 React-native 中使用 Redux Toolkit 持久化存储

问题描述

我正在将 redux-persist 与 redux 工具包一起使用。这是我的商店配置。

我以前没有实现或配置过商店。我打算在登录后保留用户状态。目前登录后,如果我在模拟器中重新加载应用程序,它总是会返回登录屏幕。

我的商店配置正确吗?

更新的商店文件:

import {configureStore} from '@reduxjs/toolkit';
import authReducer from '../features/login/authSlice';
import AsyncStorage from '@react-native-community/async-storage';
import {persistReducer, persistStore} from 'redux-persist';
import {combineReducers} from 'redux';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

const reducers = combineReducers({
  auth: authReducer,
  // other reducers goes here...
});

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
//  stateReconciler: hardSet,
};

const _persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({
  reducer: _persistedReducer,
});
export const persistor = persistStore(store);

index.js在其中包装根组件的文件PersistGate

   import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {store, persistor} from './src/stores/store';
import {Provider} from 'react-redux';
import {storeUser, storeRefreshToken} from './src/features/login/authSlice';
import {PersistGate} from 'redux-persist/lib/integration/react';

const RNRedux = () => (
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>
);

AppRegistry.registerComponent(appName, () => RNRedux);

我目前得到的错误:

在此处输入图像描述

标签: react-nativereduxredux-persistredux-toolkit

解决方案


这似乎是 redux-persist 将函数作为操作类型传递的问题,这是 Redux 开发人员不推荐的。Redux Toolkit 是使用默认值开发的,以帮助避免创建易损坏的代码。引发此错误的是 RTK 的默认中间件“serializableCheck”。此中间件可以完全禁用,也可以仅针对特定操作禁用,并且这两种方法都通过示例在此 SO question的答案中提供。此处为RTK 中间件文档以供快速参考。

这是一个适合您的一揽子解决方案:

- import {configureStore} from '@reduxjs/toolkit';
+ import {configureStore, getDefaultMiddleware} from '@reduxjs/toolkit';
...
export const store = configureStore({
  reducer: _persistedReducer,
+  middleware: getDefaultMiddleware({
+    serializableCheck: false
+  }),
});
...

推荐阅读