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

如何让useQuery等待location.state.id初始化后再调用API?

问题:useQuery提前发起请求导致调用错误API接口

现有组件通过路由传递的state参数获取数据:

HelloComponent 代码:

const HelloComponent = () => {
  const location = useLocation();

  const {isLoading, error, data} = useQuery("myQuery", () => axios.get("/api/something/" + location.state.id))

  return (<>Hello world</>)
}

父组件跳转代码:

<Link to="/something" state={{id: "myId"}}>
  ....
</Link>

API提供两个GET接口:

  • GET /api/something:返回列表数据
  • GET /api/something/{id}:返回指定ID的单条数据

当前问题:useQuery会在location.state.id初始化完成前就调用API,导致请求的是列表接口而非指定ID的单条数据接口,需要让useQuery等待location.state.id就绪后再发起请求。


解决方案

通过useQuery的enabled配置项控制查询执行时机,仅当location.state.id存在时才发起请求:

修改后的HelloComponent代码:

const HelloComponent = () => {
  const location = useLocation();
  const hasValidId = !!location.state?.id;

  const {isLoading, error, data} = useQuery(
    "myQuery", 
    () => axios.get(`/api/something/${location.state.id}`),
    { enabled: hasValidId } // 仅当ID存在时启用查询
  )

  return (<>Hello world</>)
}

关键说明:

  • enabled是useQuery的核心配置,接受布尔值,只有值为true时,查询才会自动执行。
  • !!location.state?.id用于安全判断ID是否存在:
    • 当路由state未初始化或id为空时,hasValidId为false,useQuery不会发起请求。
    • 当location.state.id就绪后,hasValidId变为true,useQuery自动触发正确的单条数据接口请求。

这种方式能从根源上阻止无效请求的发起,比在请求函数内做判断更规范高效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:18:22