连续执行两次 GET 时无法使 React axios 工作

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

我正在与 OpenWeatherMap 合作,以获取赫尔辛基等地的当前天气。

我最新的 MNWE(N 为

non
)是:

import axios from 'axios'

const apiKey = import.meta.env.VITE_OWM_API_KEY

const getCityCoordinatesApiUrl = (city) => {
    return `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
}

const getCityWeatherApiUrl = (longitude, latitude) => {
    return `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
}

const getCityWeather = (city, weatherJsonContainer) => {
    const url = getCityCoordinatesApiUrl(city)
    let longitude = null
    let latitude = null

    axios.get(url).then(response => {
        console.log("Hell", response.data)
        longitude = response.data.coord.lon
        latitude = response.data.coord.lat
    })
    .catch(error => {
        console.log("Error in getCityWeather:", error)
        alert(`Could not obtain weather of ${city}!`)
    })

    console.log("getCityWeather: received:", latitude, longitude)

    const url2 = getCityWeatherApiUrl(longitude, latitude)

    const outData = axios.get(url2).then(response => response.data)
    
    console.log("getCityWeather: outData:", outData)
}

我的问题是

longitude
latitude
保持为
null
。我该如何解决这个问题?我已经为此工作了几个小时了。

reactjs axios promise openweathermap
1个回答
0
投票

您需要等待第一个请求完成。将代码放在 .catch() 后面的 .then() 语句中

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