2016-12-02 156 views
0

我用fetch-jsonp来从darksky API的一些数据,但存储数据时,当我获取数据存储数据类型错误在阵列

constructor(props) { 
     super(props); 
     this.state = { 
      daily: [], 
      hourly: [], 
      hourlySum: '', 
      dailySum: '', 
      loading: true, 
      error: null 
    }; 
    } 

    componentDidMount() { 
    if (navigator.geolocation){ 
     function success(position) { 

     var latitude = position.coords.latitude; 
     var longitude = position.coords.longitude; 
     var results = fetchJsonp(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`) 
     .then(result => { 
      this.setState({ 
      daily: result.daily.data, 
      hourly: result.hourly.data, 
      hourlySum: result.hourly, 
      dailySum: result.daily, 
      loading: false, 
      error: null 
      }); 
     })/*.catch(err => { 
      // Something went wrong. Save the error in state and re-render. 
      this.setState({ 
       loading: false, 
       error: err 
      }); 
      });*/ 
     }; 
     function error() { 
     console.log('geolocation error') 
     }; 
     navigator.geolocation.getCurrentPosition(success.bind(this), error); 
    } 
    } 

该错误消息类型错误时,我得到一个类型错误:不能读未定义引用daily: result.daily.data财产“数据”,但因为我定义daily为数组我不明白为什么我得到一个类型错误 This参考

响应格式我没有使用爱可信(这工作),但因为同样的事情CORS我切换到JSON P.

我的工作Axios公司代码看起来像

var _this = this; 
    this.serverRequest = axios.get(`https://api.darksky.net/forecast/key/`+latitude+`,`+longitude+`?units=auto`) 
    .then(result => { 
     _this.setState({ 
     daily: result.data.daily.data, 
     hourly: result.data.hourly.data, 
     hourlySum: result.data.hourly, 
     dailySum: result.data.daily, 
     loading: false, 
     error: null 
     }); 
    }) 

在此先感谢

+0

呼叫前

fetchJsonp('/users.jsonp') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) }) 

所以,我没有看到你定义'daily'为:

查看该网页您链接样品数组。你从网上获取一些数据,看起来数据没有一个正确的'daily'命名。基本上''result.daily'似乎是未定义的。尝试注销'结果'并确认您获得了您期望的数据。 –

+0

每日数组是在构造函数中定义的。我也更新了我的问题,因为我使用axios – frisk0

回答

1

https://github.com/camsong/fetch-jsonp网站:

Make JSONP request like window.fetch 

这意味着你将需要调用response.json(),按要求fetch。你叫setState链中的另一个then()一起response.json()

+0

谢谢!按预期工作:) – frisk0