首页 > 解决方案 > store.getState 不是一个函数 Redux-persist

问题描述

我正在尝试在我的 React Native 应用程序上实现 Redux-persist。完全按照设置文档,我从这里更改了我的 store.js:

import { applyMiddleware, createStore } from 'redux';
import * as thunkMiddleware from 'redux-thunk';

import reducers from '../reducers';

let middlewares = [thunkMiddleware.default];
const store = createStore(reducers, applyMiddleware(...middlewares));

export default store;

对此:

import { applyMiddleware, createStore } from 'redux';
import * as thunkMiddleware from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import AsyncStorage from '@react-native-community/async-storage';

import reducers from '../reducers';

const persistConfig = {
    key: 'root',
    storage: AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig, reducers);

let middlewares = [thunkMiddleware.default];

export default () => {
    let store = createStore(persistedReducer, applyMiddleware(...middlewares));
    let persistor = persistStore(store);
    return { store, persistor };
};

但是现在,我得到了错误TypeError: store.getState is not a function (In 'store.getState()', 'store.getState' is undefined)

注意:我已经检查了许多关于 stackoverflow 的问题,都存在相同的 store.getState 错误,但它们的问题与我的设置不同。

编辑:提供者实现(使用 RNNv2)

import { Navigation } from 'react-native-navigation';
import { Provider } from 'react-redux';

import store from '../../shared/redux/store';
import { registerScreens } from '../view/screens';
import { initialize } from './navigation';

/**
 * Register screens and components for react native navigation
 */
registerScreens({ store, Provider });


const app = () => {
  Navigation.events().registerAppLaunchedListener(() => {
    initialize();
  });
};

export default app;

注册屏幕:

const registerComponentWithRedux = (redux: any) => (
  name: string,
  component: any,
) => {
  Navigation.registerComponentWithRedux(
    name,
    () => component,
    redux.Provider,
    redux.store,
  );
};

export function registerScreens(redux: any) {
  registerComponentWithRedux(redux)(screen, screen.default);
  ...
}

标签: reactjsreact-nativereact-reduxreact-native-navigationredux-persist

解决方案


问题在于导出,您正在导出一个返回键中存储的函数。因此,如果您在注册屏幕中更新商店引用,它将起作用。

import returnStoreAndPersistor from '../../shared/redux/store';

const {store} = returnStoreAndPersistor();
registerScreens({ store, Provider });

推荐阅读