【发布时间】:2022-11-11 20:48:33
【问题描述】:
作为一个整体,我对 React 和 Web 开发非常陌生,我知道代码的样式非常糟糕,但请多多包涵。
我正在尝试使用 openweathermap API 获取天气数据,我必须将纬度和经度用于我想要的位置,当我向它提供一个国家的首都和国家代码时,我应该从他们单独的地理编码 API 中获取我'我感兴趣。
我有点不确定如何“堆叠”这些请求,以便第一个坐标请求通过并将坐标提供给第二个天气请求。我的问题是坐标(否则我会成功)在我的下一个请求中未定义,我不知道为什么,我已经尝试了很多。
const Content = ({result}) => {
const languages = [result['languages']]
const [weather, setWeather] = useState([])
const [coordinate, setCoordinates] = useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(() => {
axios
.get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
.then(response => {
setCoordinates(response.data)
})
.then(() =>
axios
.get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
.then(response => {
setWeather(response.data)
}))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
【问题讨论】:
标签: reactjs react-hooks axios