首页 > 解决方案 > 无法保持 react-native redux 状态

问题描述

在我的 react-native 应用程序中,我尝试使用https://github.com/rt2zz/redux-persist将我的 redux 状态保存到本地存储中,并在应用程序重新启动时将其加载回来。有许多教程与官方 github 页面没有什么不同。我已经尝试了很多次,但是当我关闭应用程序并再次打开时,我的数据仍然丢失。这是我的代码的样子:

// store.js
import React from 'react';
import {createStore} from 'redux';

import {persistStore, persistReducer} from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';
import rootReducer from '../reducer/index';

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

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = createStore(persistedReducer);
const persistor = persistStore(store);

export {persistor, store};

// app.js

import {store, persistor} from "./store";

// render method returns
<Provider store={store}>
  <PersistGate loading={null} persistor={persistor}>
    // main react-navigation component
  </PersistGate>
</Provider>
// reducer/index.js
import {combineReducers} from 'redux'
import language from './language'

const reducers = combineReducers({
    language,
    ...
});

export default reducers;

当我关闭并再次打开应用程序或在命令屏幕上使用 r 刷新复古服务器时,数据会丢失。可能是什么原因?除了 redux-persist 库,我也对任何其他解决方案持开放态度。

标签: react-nativereduxreact-reduxpersistenceredux-persist

解决方案


推荐阅读