React Query未使用缓存数据反而发起API请求,求排查
问题原因及解决方法
你的问题核心是两个页面的queryKey不一致,导致React Query认为是不同的查询,从而重新发起API请求,而非读取缓存。
具体可能的原因
- 参数类型不匹配:路由Query传递的所有参数都是字符串类型,但第一个页面
filters里的state、propertyValue、loanToValue可能是数字类型。比如第一个页面state是1(数字),路由传过去后变成"1"(字符串),此时两个页面的queryKey对应位置元素类型不同,React Query会判定为不同查询。 - 参数值不一致:跳转时某些
undefined的参数被转换为空字符串,或者第二个页面解析路由参数时默认值处理不同。比如第一个页面occupancy是undefined,路由跳转时未传递该参数,但第二个页面读取router.query.occupancy得到空字符串,导致queryKey元素值不同。
解决步骤
统一参数类型和值:在第二个页面解析路由参数时,严格按照第一个页面的
filters参数类型转换:// 第二个页面代码示例(以Next.js路由为例,根据你的框架调整) import { useRouter } from 'next/router'; import { useFilteredProfiles } from './path-to-hook'; const SecondPage = () => { const router = useRouter(); // 转换参数类型,和第一个页面保持一致 const filters = { type: router.query.type || undefined, state: router.query.state ? Number(router.query.state) : undefined, occupancy: router.query.occupancy || undefined, propertyValue: router.query.propertyValue ? Number(router.query.propertyValue) : undefined, loanToValue: router.query.loanToValue ? Number(router.query.loanToValue) : undefined }; const queryResult = useFilteredProfiles(filters); // ...其他逻辑 };验证
queryKey一致性:在两个页面分别打印queryKey,确认完全一致:// 第一个页面 const queryResult = useFilteredProfiles(filters); console.log('第一个页面queryKey:', queryResult.queryKey); // 第二个页面 const queryResult = useFilteredProfiles(filters); console.log('第二个页面queryKey:', queryResult.queryKey);对比两个输出数组的每一项,确保值和类型完全相同。
优化跳转时的参数传递:过滤掉
undefined参数,避免路由传递无效值:const handleClick = () => { const queryParams = Object.fromEntries( Object.entries({ type, state, occupancy, propertyValue, loanToValue }).filter(([_, val]) => val !== undefined) ); router.push({ pathname: `${router.pathname}/profiles`, query: queryParams }); };
内容的提问来源于stack exchange,提问作者Shardul Pathak
相关产品推荐
相关产品推荐

