我正在尝试在我的React Native应用上实现Redux-persist。完全遵循setup docs之后,我从此更改了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);
...
}
答案 0 :(得分:1)
问题与导出有关,您正在导出返回键中存储的函数。因此,如果您在注册屏幕中更新商店参考,它将起作用。
import returnStoreAndPersistor from '../../shared/redux/store';
const {store} = returnStoreAndPersistor();
registerScreens({ store, Provider });
答案 1 :(得分:0)
如果您使用“ redux-persists”并从../store返回{store,persister},只需尝试一下!!!!
"stack"
答案 2 :(得分:0)
对于任何有此问题并正在使用Typescript的人(其中“ getState()”上的唯一属性是“ _persist”),问题对我而言是由于将类型的组合减速器类型设置为“ any”而引起的将商店提供给persistStore时出错:
Type AnyAction is not assignable to type {your action type}
解决上述问题后,getState问题已解决。
我通过以下操作解决了这个问题:
const _ = (state: any = 0, _: AnyAction) => state;
const root = combineReducers({
_,
applicationStatusReducer,
...
});
如果您仅向其添加操作类型为“ AnyAction”的空化器,则似乎可以解决该问题(尽管存在漏洞,但实际上并未解决根本的问题)。
答案 3 :(得分:0)
发生此问题是因为此导出默认方法而不是您执行此操作 可以这样做。
export let store = createStore(persistedReducer, applyMiddleware(...middleware));
export let persistor = persistStore(store);
很抱歉给您带来不便