【问题标题】:how to call to api once a hour with react如何通过反应每小时调用一次api
【发布时间】:2022-01-03 12:20:12
【问题描述】:

我想知道如何在第一次重新加载页面时获取 api,然后每小时再次调用一次 api 来更新我的 UI,因为默认情况下该 api 每小时更新一次

这是我的代码

const [news, setNews] = useState([])

useEffect(() => {
    setInterval(() => {
        (async () => {
            tryÏ {
                const res = await fetch(`https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`)
                const data = await res.json()
                setNews(data)
                console.log("yes")
            } catch (error) {
                console.log(error)
            }
        })()
    }, 36000000);
}, [])

使用该代码,我无法在第一次页面重新加载时获得结果,仅在一个小时后...

【问题讨论】:

  • 第一次重新加载页面时无法获得结果您需要先在 setInterval 之外调用该函数,然后在 setInterval 中调用它。

标签: javascript reactjs settimeout setinterval


【解决方案1】:

将您的 API 调用移至单独的函数。在页面加载时调用它超时:

let callApi = async () => {
        try {
            const res = await fetch(url)
            const data = await res.json()
            setNews(data)
            } catch (error) {
            console.log(error)
        }
    };

useEffect(() => {
    callApi();

    setInterval(callApi, 1000 * 60 * 60)
});

【讨论】:

    【解决方案2】:

    您可以创建另一个函数并从区间和外部调用。

    const [news, setNews] = useState([]);
    
    useEffect(() => {
      const fetchData = async () => {
        try {
          const res = await fetch(
            `https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""`
          );
          const data = await res.json();
          setNews(data);
          console.log("yes");
        } catch (error) {
          console.log(error);
        }
      };
      fetchData();
      const interval = setInterval(() => {
        fetchData();
      }, 36000000);
    
      return () => clearInterval(interval);
    }, []);
    

    【讨论】:

    • 为什么要启动间隔结束然后立即取消它?
    • @Justinas 打错了,谢谢指出。
    【解决方案3】:

    你可以试试这个代码:

    const [news, setNews] = useState([]);
      const [timer, setTimer] = useState(null);
    
      const APIResponse = async (url) => {
        try {
          const response = await fetch(url);
          const data = await response.json();
          setNews(data);
        } catch (e) {
          console.error(e);
        }
      };
    
      useEffect(() => {
        APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
        setTimer(
          setInterval(async () => {
            APIResponse("https://newsapi.org/v2/top-headlines?country=""""&apiKey=""""""""");
          }, 5000)
        );
        return () => clearInterval(timer);
      }, []);
    

    【讨论】:

    • 请解释为什么要尝试此代码以及它比任何其他答案更好/不同
    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2022-06-22
    相关资源
    最近更新 更多