我正在尝试显示来自OpenWeather API的一些数据。我可以console.log数据并查看对象,但是从那里我不知道如何获取正确的值。我将在下面粘贴一些代码。
我的问题是,无论我如何尝试从该对象中获取一些数据,我似乎都不会成功。
console.log(data)
给了我一个对象,但是每次尝试执行data.main.temp
或data.city
时,都会给我一个错误。
有什么建议吗?
state = {
temperature: null,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: undefined
}
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
const data = api_call.json();
console.log(data);
//To check after data
if(city && country){
this.setState({
//temperature: data.main.temp,
//city: data.name,
//country: data.sys.country,
//humidity: data.sys.humidity,
//description: data.weather[0].description,
error: ""
});
} else {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: "Please enter values"
});
How the object looks while fetched.
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
base: "stations"
clouds: {all: 40}
cod: 200
coord: {lon: -2.24, lat: 53.48}
dt: 1569681998
id: 2643123
main: {temp: 15.43, pressure: 1005, humidity: 87, temp_min: 12.78, temp_max: 17.78}
name: "Manchester"
答案 0 :(得分:2)
我相信x ++ y
返回了一个承诺,这就是您遇到问题的原因。
我建议您也尝试对该语句进行api_call.json()
:
await
有关const data = await api_call.json();
API的更多信息,您可以在这里找到:https://developers.google.com/web/updates/2015/03/introduction-to-fetch
干杯!
答案 1 :(得分:1)
您是否尝试过像这样使用try/catch
:
getWeather = async (e) => {
e.preventDefault();
let response = null;
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
try {
response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
const data = response.json()
data && this.setState({
temperature: data.main && data.main.temp,
city: data.name,
country: data.sys && data.sys.country,
humidity: data.sys && data.sys.humidity,
description: data.weather[0].description,
error: ""
});
} catch (error) {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: "Please enter values"
});
}
}