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

useQuery调用时data显示undefined问题排查求助

问题分析与修复方案

问题现象

API已成功拉取数据,但在React页面通过useQuery调用时,shopSplits始终显示为undefined。

核心问题排查

结合提供的代码,问题集中在以下三点:

1. QueryKey参数解构不匹配

在ShopSplits函数中,从queryKey[1]解构了id,但useQuery传入的queryKey仅包含{ Active: 0 },无id字段,导致id为undefined;同时请求URL里id和IsActive之间缺少&分隔符,造成URL格式错误。

2. 异常未向上抛出

ShopSplits的catch块仅打印错误,未重新抛出异常,React Query会默认请求成功,最终返回undefined(catch块无返回值)。

3. 异步数据打印时机错误

useQuery是异步操作,组件初始渲染时shopSplits必然是undefined,直接在组件顶层打印会捕获初始状态,而非请求完成后的有效数据。

修复代码

修复后的API调用函数

export const ShopSplits = async ({ queryKey }) => {
  try {
    // 仅解构queryKey中实际传入的Active字段
    const { Active } = queryKey[1];
    // 修正URL格式:若无需id则移除该参数,需id则确保queryKey传入id并添加&分隔
    const res = await axios.get(`/api/ShopSplits?IsActive=${Active}`);
    console.log(res);
    const data = res.data;
    console.log(data);
    // 适配API返回结构:若res.data直接是目标数据则返回res.data,否则返回data.data
    return data.data || data;
  } catch (error) {
    console.log(error);
    // 抛出异常让React Query识别请求失败
    throw error;
  }
};

修复后的useQuery调用

const { data: shopSplits, isLoading: SSL } = useQuery(
  ["Shopsplits", { Active: 0 }],
  ShopSplits
);

// 等待加载完成后再打印数据,避免捕获初始undefined
if (!SSL) {
  console.log("the splits", shopSplits);
}

额外说明

  • 若API需要id参数,需在useQuery的queryKey中补充传入{ id: 目标ID值, Active: 0 },同时将URL修正为/api/ShopSplits?id=${id}&IsActive=${Active}。
  • 务必确认API返回的数据结构:若接口直接返回res.data为目标数组/对象,无需额外取data.data,这也是导致返回undefined的常见原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:41:06