首页 > 解决方案 > 如何使用 redux-persist 在 React Native 中持久化 redux 存储

问题描述

我将 react-native 与 redux-persist 一起使用,我似乎无法让我的商店持久保存到异步存储中。根据 redux-persist github repo,这可能与从 react-native 中删除 AsyncStorage 有关,但我似乎无法弄清楚需要做些什么来解决这个问题。

当我的应用程序启动时,我在我的 redux devtools 中看到了动作persist/PERSISTpersist/REHYDRATE触发,但没有任何东西存储在异步存储中。

我以为我已经按照 redux-persist 文档的解释设置了我的文件,但我想我错过了一些东西。我对 Redux 还很陌生,所以我可能只是对一些基本的东西感到困惑。

我的 Redux.config.js 文件...

import React from 'react';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux'
import thunk from 'redux-thunk';
import { initialState } from './initialState';
import { puppyReducer } from './reducers/puppies/puppyReducer';
import { uiReducer } from './reducers/ui/uiReducer';
import { userReducer } from './reducers/user/userReducer';
import { contentReducer } from './reducers/content/contentReducer';
import { persistStore, persistReducer, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/lib/storage'
import logger from 'redux-logger';
import Navigation from './Navigation.config';
import { PersistGate } from 'redux-persist/integration/react';

const persistConfig = {
    key: 'root',
    storage: storage
}

const rootReducer = {
    dogs: puppyReducer,
    ui: uiReducer,
    user: userReducer,
    content: contentReducer
};

const reducer = persistCombineReducers(persistConfig, rootReducer);

const persistedReducer = persistReducer(persistConfig, reducer);

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(persistedReducer, initialState, composeEnhancers(applyMiddleware(thunk), applyMiddleware(logger)));

const persistor = persistStore(store);

// Wrap the redux State Provider around the Main Navigation Stack
function StateWrapper() {
    return (
        <Provider store={store}>
            <PersistGate loading={null} persistor={persistor}>
                <Navigation />
            </PersistGate>
        </Provider >
    )
}

export default App = StateWrapper;

我希望这应该在应用程序启动时加载我的持久状态,并在我的 redux 状态更改时继续更新该持久状态。就目前而言,我的状态更新正常,但没有任何内容持续存在。没有显示错误消息。

标签: react-nativereduxreact-reduxredux-persist

解决方案


我使用AsyncStorage持久化我的 redux 存储。我没有使用redux-persist的存储选项,而是从@react-native-community. 只需确保正确链接依赖项即可。

然后在我的config.js文件中,我按如下方式导入和使用 AsyncStorage。

import AsyncStorage from '@react-native-community/async-storage';

const config = {
  key: 'primary',
  keyPrefix: '', // the redux-persist default `persist:` doesn't work with some file systems
  storage: AsyncStorage,
};

您的问题也可能与keyPrefix尝试将其设置为默认值以外的某个值有关。


推荐阅读