我正在尝试创建一个React Native应用程序,该应用程序从Google API获取数据,但遇到了一些问题(未处理的JS异常:未定义不是对象(正在评估"responseData[0].destination_addresss")。
这是代码:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
} = React;
var INITIAL_DATA = [
{city: 'CityName', duration: "0 hours"},
];
var REQUEST_URL = 'https://maps.googleapis.com/maps/api/distancematrix/json?mode=driving&language=en&origins=Austin&destinations=San+Francisco&key=PRIVACY';
var AwesomeProject = React.createClass({
getInitialState: function() {
return {
data: INITIAL_DATA[0],
};
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
data: { city: responseData[0].destination_addresses[0].rendered, duration: responseData[0].rows[0].elements[0].duration.text.rendered },
});
})
.done();
},
render: function() {
return (
<View style={styles.container}>
<View style={styles.textContainer}>
<Text style={styles.city}>
{this.state.data.city}
</Text>
<Text style={styles.text}>
{this.state.data.duration}
</Text>
</View>
</View>
);
}
});
var Dimensions = require('Dimensions');
var windowSize = Dimensions.get('window');
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
textContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
city: {
fontSize: 30,
textAlign: 'center',
margin: 10,
},
text: {
fontSize: 18,
paddingLeft: 20,
paddingRight: 20,
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
buttonContainer: {
bottom: 0,
flex: .1,
width: windowSize.width,
backgroundColor: '#eee',
},
button: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
fontSize: 30,
color: '#666666',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
这就是我正在解析的json响应:
{
"destination_addresses" : [ "San Francisco, CA, USA" ],
"origin_addresses" : [ "Austin, TX, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2,830 km",
"value" : 2830409
},
"duration" : {
"text" : "1 day 1 hour",
"value" : 90952
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我认为您需要检查状态代码。
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
if(responseData.status === "OK"){
this.setState({
data: { city: responseData[0].destination_addresses[0].rendered,duration: responseData[0].rows[0].elements[0].duration.text.rendered },
});
}else{
// Do something
}
})
.done();