【问题标题】:async axios get call axios returns nothingasync axios get call axios 什么也不返回
【发布时间】:2022-02-11 04:33:25
【问题描述】:

我正在尝试使用axiosopenweathermaps 获取当前温度。

我可以将我的网址放入浏览器中,它工作正常。但是当我尝试使用正确的 url 进行 axios 调用时,它不会调用事件。

以下是相关代码部分:

function Overview() {
  const [temperature, setTemperature] = useState('')
  const API_KEY = '{apikey}'

  const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
      2,
    )}&appid=${API_KEY}`

    console.log('my provided url is set to:', url)

    const response = await axios.get(url)
    if (response.data) {
      setTemperature(response.data.main.temp)
    }
  }, [latitude, longitude])

  useEffect(() => {
    getTemperature().catch(console.error)
  }, [getTemperature])

  return <>{temperature ? temperature : 'no data'}</>
}

任何关于我哪里出错的帮助都会很棒,因为我只是看不到我的错误!

【问题讨论】:

  • 与您的帖子无关:出于安全原因,您可以用伪造的 API 密钥替换或从帖子中删除吗?
  • 其他快速问题:为什么要再次等待await response.data?.main?.temp 中的同步响应? API 是否期望编码的 URI 格式?
  • 我刚刚更新到我原来的,我一直在做一些测试
  • 设置用户代理可能会有所帮助,stackoverflow.com/a/67486713/2122822 还尝试查看在有效请求中发送的标头
  • 您已经声明了一个名为 setTemperature (const setTemperature = async () =&gt; {}) 的函数,但正在尝试调用一个名为 getTemperature (useEffect(() =&gt; {getTemperature()}, [latitude, longitude])) 的函数。也许这只是您的示例代码而不是您的实际代码?另请注意,setTemperature 已经存在,因为它是您的 const [temperature, setTemperature] = useState(''); 的一部分

标签: javascript reactjs typescript async-await axios


【解决方案1】:

您在浏览器上运行的 URL 表明您的 API 密钥是正确的。现在,请确保您的 URL 中的变量已从代码中正确设置,尤其是 API 密钥。你可以 console.log 他们确定。通过了,下面的最小代码就可以了。

import {useCallback, useEffect} from 'react';
import axios from 'axios';

function Overview() {

// YOUR_INITIAL_STATE rather be undefined 
const [temperature, setTemperature] = useState(YOUR_INITIAL_STATE);

const API_KEY = 'YOUR_API_KEY';

const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

   console.log("my provided url is set to:", url);

    const response = await axios.get(url);
    if(response.data){
      setTemperature(response.data.main.temp);
    }
// only call the functtion when these deps change
}, [latitude, longitude])

useEffect(() => {
// Check the error for further debbugging
getTemperature()
.catch(console.error);

}, [getTemperature])

      return (
            <>
          {temperature ? temperature : "no data"} 
            </>
        );
}

【讨论】:

  • 嘿不幸的是这仍然失败,我不知道为什么,我在我的浏览器中记录了相同的 url,但它仍然无法正常工作。这可能与它对本机和博览会的反应有关吗?我很困惑
  • 为了让它更奇怪,我只是在一个空的 react 项目中运行它,它可以工作吗?也许它与 react native 和 expo 有关?
  • 您始终可以在codesandbox 上的裸react-expo 项目上运行代码来消除您的疑虑。通过了,你需要为人们提供更多的背景来帮助你。
【解决方案2】:

看起来您的箭头函数正在递归调用自身:

const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};

您的代码没有显示调用它的位置。可能它需要是这样的:

const setTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    return response.data.main.temp;
};

也许只需要一个字母的变化:

const getTemperature = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`);
    setTemperature(response.data.main.temp);
};

感谢@devklick

【讨论】:

  • 嗨!我刚刚尝试了上面的答案,我认为它与 expo 和使用 expo 而不是我的 ip 有关!当我尝试在本地反应项目中重新运行它时,它运行良好。我发现了一些关于堆栈溢出的类似问题,建议针对我的 ip 运行查询!
  • 很抱歉,我无法回答关于 expo 与您的 ip 的问题。 AFAICT 递归调用不应该在任何地方工作。根据@devklick 的评论,您可能只需将const setTemperature = async () =&gt; { 更改为const getTemperature = async () =&gt; {
  • @David,这是我在编辑他的问题时犯的错字,在原始问题中找不到。感谢您指出。它已被另一位编辑修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 2020-07-25
  • 2021-08-08
  • 2021-02-03
  • 2021-05-11
相关资源
最近更新 更多