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

使用TanStack React Query时依赖查询引发无限加载问题求助

解决React Query依赖查询无限加载问题

问题根源分析

你的代码存在两个核心问题导致无限加载:

  • 渲染逻辑完全写反:当前逻辑是加载状态时显示下拉框,加载完成时显示加载提示,这会让你误以为加载状态一直未结束。
  • 无效请求触发自动重试:第二个查询的enabled仅判断fire的状态,未校验channelId是否存在。当user数据还未加载完成时,channelId为undefined,此时触发的请求会返回错误,而React Query默认会自动重试失败请求,形成无限加载循环。

修复后的代码

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

const fetchUserByEmail = (email) => {
  return axios.get(`http://localhost:4000/users/${email}`);
};

const fetchCoursesByChannelId = (channelId) => {
  return axios.get(`http://localhost:4000/channels/${channelId}`);
};

export const DependentQueriesPage = ({ email }) => {
  const [fire, setFire] = useState("");
  const [water, setWater] = useState("");

  const { isLoading: isUserLoading, data: user } = useQuery(
    ["user", email],
    () => fetchUserByEmail(email)
  );
  const channelId = user?.data?.channelId;

  const { isLoading: isSubUserLoading, data: courses, isError } = useQuery(
    ["courses", channelId],
    () => fetchCoursesByChannelId(channelId),
    {
      // 同时满足fire有效且channelId存在才触发查询
      enabled: Boolean(fire) && Boolean(channelId),
      // 可选:关闭自动重试,避免错误时无限循环
      retry: false,
    }
  );

  // 处理第一个查询的加载状态
  if (isUserLoading) {
    return <p>Loading user data...</p>;
  }

  return (
    <>
      <div>DependentQueries</div>
      <select onChange={(e) => setFire(e.target.value)}>
        <option value="">select fire</option>
        <option value="one">one</option>
        <option value="oned">oned</option>
      </select>

      {/* 修复条件判断:加载时显示spinner,完成/错误时显示下拉框 */}
      {isSubUserLoading ? (
        <p>water spinner ...</p>
      ) : (
        <select onChange={(e) => setWater(e.target.value)}>
          <option value="">select water</option>
          <option value="one">one</option>
          <option value="oned">oned</option>
        </select>
      )}

      {/* 可选:显示错误提示 */}
      {isError && <p>Failed to load courses</p>}
    </>
  );
};

关键修复点

  • 反转渲染条件:调换isSubUserLoading的判断逻辑,加载状态显示spinner,加载完成后显示下拉框。
  • 完善enabled触发条件:新增Boolean(channelId)校验,确保只有当fire被选择且channelId已获取到的情况下,才触发第二个查询。
  • 优化select的onChange逻辑:改为使用选中值e.target.value,同时给默认option设置空值,确保初始状态fire为空。
  • 添加错误处理:可选关闭自动重试或显示错误信息,避免错误请求导致的无限重试。
  • 处理第一个查询的加载状态:在user数据加载完成前,先显示对应加载提示,避免页面状态混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:43:08