每20秒钟致电API,然后停止特定响应

发布于 2025-02-09 19:45:00 字数 322 浏览 1 评论 0原文

从渲染组件的那一刻起,我想每20秒钟致电一次API,并且在提供特定响应时必须停止API调用。

解释更多。有一个API获取方法,它将像下面一样发送响应。 {firstWork:'Success',二项工作:'成功',第三项工作:'过程中'}

所以我想从组件渲染的点开始定期/反复(每20秒)调用此API(每20秒)直到所有这些变成“成功”。 {firstWork:'Success',秒为:'成功',第三项:'Success'}

当我得到上述响应时,我应该停止调用API GET方法。如何在ReactJ中实现它?

I want to call my API every 20 seconds from the moment where the component is rendered and the api calling has to stop when it provides a specific response.

Explaining more. There is an API get method which will send a response like below.
{firstWork : 'Success' , SecondWork : 'Success' , ThirdWork : 'IN-Progress'}

So I want to call this API periodically/repeatedly(every 20sec) from the point where the Component is Rendered and till all these becomes 'Success'.
{firstWork : 'Success' , SecondWork : 'Success' , ThirdWork : 'Success'}

When I get the above response I should Stop calling the API get method. How can I achieve it in ReactJS?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琴流音 2025-02-16 19:45:00

您可以通过在组件中设置setInterval来实现这一目标。

import { useEffect } from "react"

const Component = () => {
  useEffect(() => {
    const interval = setInterval(() => {
      fetch("/yourApiEndpoint")
        .then(res => res.json())
        .then(json => {
          if(json.thirdWork === "Success"){
            clearInterval(interval)
          }
        })
    }, 20*1000)
  },[])

  return <p>component</p>
}

You can achieve that by setting a setInterval inside your component.

import { useEffect } from "react"

const Component = () => {
  useEffect(() => {
    const interval = setInterval(() => {
      fetch("/yourApiEndpoint")
        .then(res => res.json())
        .then(json => {
          if(json.thirdWork === "Success"){
            clearInterval(interval)
          }
        })
    }, 20*1000)
  },[])

  return <p>component</p>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文