如何在 React Native 中持久化 Redux 数据

How to persist redux data in react native

我一直在努力解决这个问题,现在这是一个非常简单的问题我需要一种方法将我的数据从 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,它适用于多个项目。看看它是否适合你。

store.js

import { applyMiddleware, createStore, compose } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import AsyncStorage from "@react-native-async-storage/async-storage";
import thunkMiddleware from "redux-thunk";
import { createLogger } from "redux-logger";
import reducer from "./reducers/";

const enhancers = [
    applyMiddleware(
        thunkMiddleware,
        createLogger({
            collapsed: true,
            // eslint-disable-next-line no-undef
            predicate: () => __DEV__,
        })
    ),
];

/* eslint-disable no-undef */
const composeEnhancers =
    (__DEV__ &&
        typeof window !== "undefined" &&
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
    compose;
/* eslint-enable no-undef */

const enhancer = composeEnhancers(...enhancers);

const persistConfig = {
    key: "root",
    storage: AsyncStorage,
    blacklist: [],
};

const persistedReducer = persistReducer(persistConfig, reducer);
export const store = createStore(persistedReducer, {}, enhancer);
export const persistor = persistStore(store);

authReducer.js

import {AuthResponse} from '../../types/AuthResponse';
import {AuthReduxAction} from '../../types/ReduxActions';
import {SET_USER_DETAILS} from '../constants';


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 authReducer;

index.js(与 authReducer.js 相同的位置)

import { combineReducers } from 'redux';

import authReducer from './authReducer';
import toastReducer from './toastReducer';

export default combineReducers({
    authReducer ,
    toastReducer
});