我getWeather
从我编写的另一个 .js 文件中导入该函数。结果是一个 json blob。我已经验证我得到了 JSON blob,但是当我尝试调用该getWeather
函数并使用 .then 等待响应并设置我的状态时,我得到了一个 TypeError。
getWeather(parseFloat(lat),parseFloat(long)).then((data) =>{
this.setState({weatherType: data.currently.icon, temp: data.currently.temperature})
return data
}).catch((error) => {
console.log(error.message);
})
该getWeather
功能是在这里:
export function getWeather(lat,long) {
const params = {
headers: {
"content-type": "application/json; charset=UTF-8",
"Access-Control-Allow-Origin": "*"
},
method: "GET"
};
fetch(`https://api.com/mykey/${lat},${long}`, params)
.then(function (data) {
return data.json();
})
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error);
});
}
您需return fetch()
要这样做才能从另一个函数访问承诺。另外,我可能会在调用函数中处理日志记录和错误,因为当您记录数据时不再返回它。
export function getWeather(lat,long) {
const params = {
headers: {
"content-type": "application/json; charset=UTF-8",
"Access-Control-Allow-Origin": "*"
},
method: "GET"
};
return fetch(`https://api.com/mykey/${lat},${long}`, params)
.then(function (data) {
if (!data.ok) { return new Error('custom error message here') }
return data.json();
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句