react-native - 在 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);
我目前得到的错误:
解决方案
这似乎是 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
+ }),
});
...
推荐阅读
- mysql - 如何将连接失败的 MySQL 转发到错误页面 (500)
- azure - Azure AD OAuth2.0:我没有获得刷新令牌
- swift - ARKit ARSCNView.snapshot() 内存泄漏
- r - 如何在 R 中的数据库连接上的过滤器中使用字符向量?
- wordpress - 将 Gravity Forms 发送到 3rd Party API 并在发送前在 API 中检查重复项
- sql - SQL Server 错误 42000 - 必须声明标量变量
- python - (m, 2), (n, 2) 数组的有效添加
- android - NestedScroll 视图检测滚动状态
- elasticsearch - Elasticsearch 不显示具有相同匹配的所有版本
- c# - 为 ASP.NET Web 窗体 ApiController 启用 Http 选项预检请求