【问题标题】:How to persist redux store to local storage rather than async storage in react native如何将redux存储持久化到本地存储而不是反应原生的异步存储
【发布时间】:2021-03-17 18:44:28
【问题描述】:

我正在使用redux-persist 来保持我的应用程序的状态。默认情况下,它在AsyncStorage 中保持状态,但我希望它在localStorage 中。就react-native 而言,官方文档中对此一无所知。 这是我到目前为止的代码:

import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/es/storage';

const config = {
    key: 'root',
    storage,
    debug: true
  }

export const ConfigureStore = () => {
    const store = createStore(
        persistCombineReducers(config,{
            dishes,
            comments,
            promotions,
            leaders,
            favorite
        }),
        applyMiddleware(thunk)
    );

    const persistor = persistStore(store)

    return {persistor, store};
}

我可以这样做吗:

import storage from 'redux-persist/es/localStorage';
...
storage: storage

如果有人曾经使用过它,请帮助我解决这个问题。谢谢!

【问题讨论】:

    标签: reactjs react-native redux redux-persist


    【解决方案1】:

    我注意到的一件事是你导入说

    从 'redux-persist/es/storage' 导入存储; 但在文档中使用 从'redux-persist/lib/storage'导入存储

    否则,您可以像文档中那样使用这种方法。

    import { createStore } from 'redux'
    import { persistStore, persistReducer } from 'redux-persist'
    import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
    
    import rootReducer from './reducers'
    
    const persistConfig = {
      key: 'root',
      storage,
    }
    
    const persistedReducer = persistReducer(persistConfig, rootReducer)
    
    export default () => {
      let store = createStore(persistedReducer)
      let persistor = persistStore(store)
      return { store, persistor }
    }

    import { PersistGate } from 'redux-persist/integration/react'
    
    // ... normal setup, create store and persistor, import components etc.
    
    const App = () => {
      return (
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <RootComponent />
          </PersistGate>
        </Provider>
      );
    };

    【讨论】:

      猜你喜欢
      • 2019-09-20
      • 2021-03-17
      • 2021-08-29
      • 2021-12-07
      • 2019-03-28
      • 1970-01-01
      • 2020-07-09
      • 2019-09-20
      • 2017-01-12
      相关资源
      最近更新 更多