You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用react-query重复请求同一API直至满足指定条件?

使用React Query实现轮询直到目标字段出现

要实现发送请求后检查响应字段,找到则停止,否则持续轮询的需求,你可以利用React Query的refetchInterval动态配置+状态控制来实现,核心思路是通过状态判断是否终止轮询,每次请求成功后校验目标字段。

实现代码

import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';

// 封装成自定义Hook复用
const usePollForTargetField = (testDataId) => {
  // 控制是否停止轮询的状态
  const [stopPolling, setStopPolling] = useState(false);

  const queryResult = useQuery({
    queryKey: ['test', testDataId],
    queryFn: () => fetchTestData(testDataId),
    // 动态设置轮询间隔:停止时设为false,否则设为轮询间隔(单位:毫秒)
    refetchInterval: stopPolling ? false : 1000,
    // 请求成功后检查目标字段
    onSuccess: (response) => {
      // 替换为你的实际字段判断逻辑,比如检查response中是否存在targetField
      if (response?.targetField) {
        setStopPolling(true); // 满足条件,停止轮询
      }
    },
    // 可选:请求失败时自动重试(根据业务需求调整)
    refetchOnError: true,
    // 可选:页面失去焦点时停止轮询,重新获取焦点后继续
    refetchOnWindowFocus: !stopPolling,
  });

  return { ...queryResult, stopPolling };
};

关键逻辑说明

  • stopPolling状态:作为轮询的开关,初始为false,当检测到目标字段后设为true,触发refetchInterval变为false,终止轮询。
  • refetchInterval:动态值,根据stopPolling状态决定是否继续轮询,你可以根据业务需求调整轮询间隔(比如2000毫秒)。
  • onSuccess回调:每次请求成功后执行字段校验,这是判断是否停止轮询的核心节点。
  • 可选配置:refetchOnError控制请求失败后是否重试,refetchOnWindowFocus控制页面焦点变化时的轮询行为,可按需开启。

组件中使用

const TestComponent = ({ testDataId }) => {
  const { data, isLoading, isError, stopPolling } = usePollForTargetField(testDataId);

  if (isLoading) return <div>正在查询...</div>;
  if (isError) return <div>请求出错,请稍后重试</div>;
  if (stopPolling) return <div>已找到目标字段:{data.targetField}</div>;

  return <div>持续轮询中...</div>;
};

内容的提问来源于stack exchange,提问作者Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:55:28