如何让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自动触发正确的单条数据接口请求。
- 当路由state未初始化或
这种方式能从根源上阻止无效请求的发起,比在请求函数内做判断更规范高效。
内容的提问来源于stack exchange,提问作者Weeedooo
相关产品推荐
相关产品推荐

