无效的挂钩调用试图在反应中发出 axios get 请求

Invalid hook call trying to make an axios get request in react

我正在用 React 重新创建一个简单的天气应用程序,但在创建一个非常简单的 API 调用时遇到了很多麻烦。我在这里、youtube 等上尝试了很多方法,但不断出现错误。我目前的代码是:

import Axios from 'axios';
import { Home } from '../components/Home'
import React, {useState, useEffect} from 'react'

var weatherApiRootUrl = 'https://api.openweathermap.org';
var weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';


//function to generate weather URL. fetches lat/lon and creates new url
function GetWeatherUrl(loc){
  const [weatherLink, setWeatherLink] = useState("");

  const getCoordinates = () => {
    Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`).then(
      (response)=>{
        console.log(response);
        setWeatherLink(`${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`);
      }
    );
  };
return(
  <div>
    {weatherLink}
  </div>
);
  
}

export{
  GetWeatherUrl
}

此文件的目的只是使用用户输入(由变量 loc 设计的城市名称)来获取输入城市的 lat/lon 坐标,因为第二个 link 获取天气信息。用户输入由另一个组件处理并且工作正常。

我打算让这段代码做的是使用 loc 获取纬度和经度数据,并使用这些数字生成新的 link 来获取天气数据。天气数据将通过对另一个文件的不同 api 调用来完成。此当前文件的工作方法应该可用于将来用于获取天气的文件,所以这是一种合二为一的方式。

我需要生成的 weatherLink 才能导出来执行此操作,所以我真的更喜欢一个允许这样做的解决方案。我原本打算导出原始 lat/lon 数据并将它们用于新文件中的调用,就像我在此处对 loc 所做的那样,但我决定将完整的 link 作为字符串返回也许会更容易。真的很感谢有人在这方面的帮助它让我沮丧的时间比它应该的要长!

不是真的需要,但如果有帮助,这里是该网站的非反应版本:https://giovannimalcolm.github.io/weather-dashboard/

这可以很容易地解决,根本不需要使用 React,因为它不是一个组件,本身没有任何渲染逻辑:

import Axios from 'axios';

const weatherApiRootUrl = 'https://api.openweathermap.org';
const weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';

export async function GetWeatherUrl(loc) {
    const response = await Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`);
    return `${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`;
}

然后在需要用到天气URL的地方,需要记住GetWeatherUrlreturns一个承诺,所以你必须等待它(或像处理任何其他承诺一样处理它):

const myFn = async () => {
    const weatherUrl = await GetWeatherUrl(loc);
    const weatherUrlData = await Axios.get(weatherUrl);
};

myFn();