【发布时间】:2020-01-28 13:06:15
【问题描述】:
我正在尝试显示来自 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"
【问题讨论】:
-
您能否告诉我们您在尝试访问所需数据时遇到了什么样的错误?
-
是的,对不起,它来了:× 未处理的拒绝(TypeError):无法读取未定义的属性“temp”