我使用fetch-jsonp从darksky api获取一些数据,但是当我获取数据时,我在存储数据时得到一个TypeError
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);
}
}
错误消息是TypeError:无法读取属性'数据'未定义的引用daily: result.daily.data
,但因为我将daily
定义为数组我不明白为什么我得到一个TypeError
This是参考的响应格式
我使用Axios做了同样的事情(有效),但由于CORS,我改用了JSONP。
我的工作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
});
})
提前致谢