我正在尝试在我的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)。
注意:我用相同的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);
...
}发布于 2019-07-24 02:20:08
问题出在导出时,您正在导出一个在键中返回store的函数。因此,如果您在注册屏幕中更新存储引用,它将会起作用。
import returnStoreAndPersistor from '../../shared/redux/store';
const {store} = returnStoreAndPersistor();
registerScreens({ store, Provider });发布于 2019-10-26 05:34:57
如果你使用'redux-persists‘并从../store返回{store,persistor},试试这个!
import returnStoreAndPersistor from "../../store";
const { store } = returnStoreAndPersistor()
console.log(store.getState())发布于 2020-04-22 15:37:08
对于任何有这个问题的人来说&正在使用Typescript,其中"getState()“上的唯一属性是"_persist",这个问题对我来说是由于将你的存储提供给persistStore时的类型错误而导致的,将你的组合reducers的类型设置为"any”:
Type AnyAction is not assignable to type {your action type}
当我修复上面的问题时,getState问题就解决了。
我通过这样做解决了这个问题:
const _ = (state: any = 0, _: AnyAction) => state;
const root = combineReducers({
_,
applicationStatusReducer,
...
});如果你只是添加一个操作类型为"AnyAction“的空的reducer,它似乎解决了问题(尽管是以一种老生常谈的/并不是真正解决底层问题的方式)。
https://stackoverflow.com/questions/57169336
复制相似问题