【发布时间】:2019-08-11 12:04:30
【问题描述】:
我目前正在开发一个第一次使用 react-native 的应用程序,
但我正在努力添加 redux。
我收到此错误TypeError: Cannot read property 'getState' of undefined,但我不知道如何解决。
这是我的代码:
import React from "react";
import Home from "./home";
import { store } from "./redux/store";
import { Provider } from "react-redux";
/* @flow */
import { View, StyleSheet } from "react-native";
class App extends React.Component {
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<Home />
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
store.js:
import { applyMiddleware, createStore } from "redux";
import logger from "redux-logger";
import reducer from "./reducer";
const middlewares = [logger];
const store = createStore(reducer, applyMiddleware(...middlewares));
export default store;
reducer.js:
import { combineReducers } from "redux";
import mapReducer from "../redux/maps/maps-reducer";
export default combineReducers({
map: mapReducer
});
maps-action.js:
import MAPSActionTypes from './maps-action-types';
export const currentlocation = () => ({
console.log(${location});
type : MAPSActionTypes.GET_CURRENT_LOCATION
});
maps-reducer.js:
import MAPSActionTypes from "./mapsactiontypes";
const INITIAL_STATE = {
location: {}
};
const mapReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case MAPSActionTypes.GET_CURRENT_LOCATION:
return {
...state,
location: action.payload
};
default:
return state;
}
}
export default mapReducer;
home.js:
import React from 'react';
import {
StyleSheet,
View,
Text,
} from 'react-native';
import {connect} from 'react-redux'
const Home = (props) => {
return (
<View style={styles.container}>
<Text>welcome</Text>
<Text>{props.location}</Text>
</View>
);
};
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
}
});
const mapStateToProps = (state) => {
return {
location: state.map.location
}
}
export default connect(mapStateToProps)(Home);
我很乐意听到更多的澄清或更多的细节。 如果有人可以帮助我解决这个问题,我将非常感激。
【问题讨论】:
-
也许您可以显示更详细的堆栈跟踪以及如何连接您正在调用 redux 操作的组件?
-
@Clarity 我编辑了帖子,你现在可以检查一下吗?
-
代码看起来不错,你能显示完整的堆栈跟踪吗?
-
代替这个
location: state.map.location试试这个location: state.location。您的状态中没有map变量。
标签: reactjs react-native react-redux