【发布时间】:2021-11-18 02:59:36
【问题描述】:
我一直在努力解决这个问题,而现在这是一个非常简单的问题我需要一种方法将我的数据从 redux 持久化到 react native 的本地存储中我已经尝试过使用 redux-persist 库等多种方法,但我仍然一直没能破解...有没有人找到解决这个问题的方法,我对所有方法持开放态度。
这是我用于 redux-persist 库的代码
store.ts
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import {persistStore} from 'redux-persist';
import authReducer from './reducers/authReducer';
import toastReducer from './reducers/toastReducer';
const rootReducer = combineReducers({
toast: toastReducer,
auth: authReducer,
});
export const Store = createStore(rootReducer, applyMiddleware(thunk));
export const PersistedStore = persistStore(Store);
export type RootState = ReturnType<typeof Store.getState>;
export type AppDispatch = typeof Store.dispatch;
authReducer.ts
import AsyncStorage from '@react-native-async-storage/async-storage';
import {persistReducer} from 'redux-persist';
import {AuthResponse} from '../../types/AuthResponse';
import {AuthReduxAction} from '../../types/ReduxActions';
import {SET_USER_DETAILS} from '../constants';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
};
interface State {
userDetails: AuthResponse;
}
const initialState: State = {
userDetails: {},
};
const authReducer: (
state: State,
action: AuthReduxAction,
) => State | Promise<State> = async (state = initialState, action) => {
switch (action.type) {
case SET_USER_DETAILS:
// Saving user details to local storage
return {...state, userDetails: action.payload};
default:
return state;
}
};
export default persistReducer(persistConfig, authReducer);
App.tsx
import React from 'react';
import Routes from './Routes';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
import {LogBox} from 'react-native';
import {PersistedStore, Store} from './redux/store';
LogBox.ignoreLogs(['new NativeEventEmitter']);
const App = () => {
return (
<Provider store={Store}>
<PersistGate loading={null} persistor={PersistedStore}>
<Routes />
</PersistGate>
</Provider>
);
};
export default App;
这是我从 redux 存储中打印出数据(在本例中为身份验证数据)时得到的响应:
{"_U": 0, "_V": 0, "_W": null, "_X": null, "_persist": {"rehydrated": true, "version": -1}}
任何帮助将不胜感激 谢谢
【问题讨论】:
-
“我已经尝试使用多种方法,例如 redux-persist 库,但我仍然无法破解它” - 向我们展示您的代码,然后使用
redux-persist.我们还能如何帮助您?我们不是通灵者。 -
那么究竟是什么问题?
-
数据没有被持久化,当我重新启动我的应用程序并从redux打印出数据时,响应不包括我插入的数据,而且我不知道我是否应该使用我的@987654329 @ 方法在我使用
combineReducer方法的每个单独的 reducer 或我的 rootReducer 上...... -
你不应该在你的 reducer 中使用任何持久化代码:那是 IO,reducer 应该是没有副作用的纯函数(尤其包括 IO)。而是有一个调用持久性库的操作,并在适当的时候触发该操作(这是 not 每次您的 Redux 状态发生突变时,因为 Redux 状态包括临时状态和其他不需要的无关紧要的更改被持久化)。
-
我不认为有一种方法可以使用此库以编程方式将状态保存在本地存储中,因为它还对如何使用它进行了零自定义,我可以将状态手动保存到本地存储中,但是您能否提供一个代码 sn-p 将状态从本地存储加载到 redux 存储然后加载整个应用程序,因为我需要应用程序启动时的所有数据这就是
PersistGate组件实现的目标
标签: react-native redux react-redux