React Native fetch()不起作用 [英] React Native fetch() not working

查看:203
本文介绍了React Native fetch()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个从Google API获取数据的React Native应用程序,但遇到了一些问题(未处理的JS异常:未定义不是一个对象(评估'responseData [0] .destination_addresses'))。



以下是代码:

 '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=隐私';
$ b $ var var AwesomeProject = React.createClass({
getInitialState:function(){
return {
data:INITIAL_DATA [0],
};
},

componentDidMount:function(){
this.fetchData();
},

fetchData:function(){$ ((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},$ b ();
})
.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。持续时间}
< / 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:'中心',
},
城市:{
fontSize:30,
textAlign:'center',
保证金:10,
},
text:{
fontSize:18,
paddingLeft:20,
paddingRight:20,
textAlign:'center',
color:'#333333',
marginBottom:5,
},
buttonContainer:{
bottom:0,
flex:.1,
width:windowSize.width,
backgroundColor:'#eee',
},
按钮:{
flex:1,
alignItems:'center',
justifyContent:'center',
},
buttonText:{
fontSize:30,
color:'#666666',
},
});


AppRegistry.registerComponent('AwesomeProject',()=> AwesomeProject);

以下是我解析的json响应:

  {
destination_addresses:[旧金山,CA,美国],
origin_addresses:[美国德克萨斯州奥斯汀] ,
rows:[
{
elements:[
{
distance:{
text:2,830 km ,
value:2830409
},
duration:{
text:1天1小时,
值:90952
},
status:OK
}
]
}
],
status:OK


解决方案

我相信您需要检查状态代码。

  fetch(REQUEST_URL)
.then((response)=> response.json())$ ((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 {
//做某事
}
})
.done();


I am trying to create a React Native app which fetches data from Google APIs but I am experiencing some issues (Unhandled JS Exception: undefined is not an object (evaluating 'responseData[0].destination_addresses') ).

Here is the code:

'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);

And this the the json response I am parsing:

{
   "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"
}

解决方案

I believe you need to check for status code.

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();

这篇关于React Native fetch()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆