使用位置API获取天气详情-BUG(REACT JS)

问题描述 投票:0回答:1

我才13岁,请大家乖乖的

我目前正在尝试制作一个基于天气 API 显示信息的天气应用程序,该应用程序根据用户的位置获取信息。如果您一定要知道,我正在使用 Open Weather api 和 IPInfo 进行地理定位。如果您需要任何进一步的信息来回答问题,请告诉我。

async function getCity() {
    let response = await fetch("https://ipinfo.io/json?token=MYTOKEN");
    let data = await response.json();
    let City = data.city;
    return String((City.replace(\/s/g, "")).toLowerCase()) // city name needs to be in all lower case no spaces for API url
}
async function getWeatherInfo() {
    let apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=imperial&q=" + getCity() + "&appid=MYAPIKEY";
    let weatherResponse = await fetch(apiUrl);
    let weatherData = await weatherResponse.json();
    console.log(weatherData.main.temp);
}
getWeatherInfo();

我期待程序自动获取用户的城市,然后获取该城市的天气信息。但是,如果只是给我错误:

1

reactjs api weather
1个回答
0
投票

这是一个很好的问题,你才 13 岁,所以你应该为自己走在正确的道路上感到自豪。

你的getCity()是异步函数,JS是同步的。 当您在 getWeatherInfo() 中调用 getCity() 来设置“apiURL”时,它不会立即返回值,因此未定义。

解决此问题的一种方法是在调用 getWeatherInfo() 之前设置城市。

您可以将其分配给一个变量,然后在后续调用中使用该变量。

© www.soinside.com 2019 - 2024. All rights reserved.