React Native配置Redux/Thunk/Persist报错:store.getState不是函数
解决Redux配置中的
typeError: store.getState is not a function错误 嘿,我一眼就看到问题出在哪了——你的configureStore.tsx导出的是一个函数,但在App.tsx里你直接把这个函数当成了Redux store对象传给了Provider!函数本身当然没有getState方法,这就是报错的根源。
另外你还漏掉了redux-persist必需的PersistGate组件,它负责在持久化数据加载完成后再渲染你的应用,否则可能会出现数据不一致的问题。
修正步骤:
- 在
App.tsx中调用导出的configureStore函数,获取真正的store和persistor实例 - 用
PersistGate包裹你的根组件
修正后的代码:
App.tsx
import React from 'react'; import Drawer from './PreApp'; import {Provider} from 'react-redux'; import configureStore from './redux/configureStore'; import {PersistGate} from 'redux-persist/integration/react'; // 调用函数拿到实际的store和persistor实例 const { store, persistor } = configureStore(); const App = () => { return ( <Provider store={store}> {/* PersistGate会等待持久化数据加载完成后再渲染Drawer */} <PersistGate loading={null} persistor={persistor}> <Drawer /> </PersistGate> </Provider> ); }; export default App;
额外优化:configureStore.tsx
你可以简化storage的导入,因为redux-persist/lib/storage在React Native环境下默认就是AsyncStorage,不需要额外导入@react-native-community/async-storage:
import {createStore} from 'redux'; import {rootReducer} from './reducers'; import {persistStore, persistReducer} from 'redux-persist'; import storage from 'redux-persist/lib/storage'; // RN环境下默认对应AsyncStorage import {applyMiddleware} from 'redux'; import thunk from 'redux-thunk'; const persistConfig = { key: 'root', storage, // 直接使用导入的storage }; const persistedReducer = persistReducer(persistConfig, rootReducer); export default () => { let store = createStore(persistedReducer, applyMiddleware(thunk)); let persistor = persistStore(store); return {store, persistor}; };
这样修改后,你的Redux store就能正常工作,redux-thunk和redux-persist的配置也会生效啦!
内容的提问来源于stack exchange,提问作者SzymkowskiDev
相关产品推荐
相关产品推荐

