React Query使用Infinite Query对接Edamam API出现重复拉取数据问题
问题排查&修复方案
问题点
- 核心问题:参数传递不匹配
你定义getRecipes函数时接收的是解构参数{ pageParam },但在useInfiniteQuery的查询函数中,你直接把pageParam的值作为参数传给getRecipes,相当于传入的是字符串URL,函数内部解构pageParam必然得到undefined,所以每次请求都会走初始地址的逻辑,永远拉取第一页数据,就出现了重复拉取同一批的问题。 - 无限加载触发逻辑缺少边界判断
你在useEffect中只要inView为真就调用fetchNextPage,没有判断是否还有下一页(hasNextPage)、是否正在拉取下一页(isFetchingNextPage),会导致重复触发无效请求。 - 下一页参数获取缺少容错处理
当翻到最后一页时,Edamam API返回的_links中不存在next字段,你直接取lastPage._links.next.href会抛出异常,导致hasNextPage的判断逻辑异常。
修正后代码
// 直接接收pageParam参数,无需解构 const getRecipes = async (pageParam) => { try { const path = pageParam ? pageParam : `https://api.edamam.com/api/recipes/v2?q=${query}&app_id=${process.env.REACT_APP_APP_ID}&app_key=${process.env.REACT_APP_API_KEY}&type=public`; const response = await axios.get(path); return response.data; } catch (error) { console.log(error); } } const { ref, inView } = useInView(); const { data, isFetching, isFetchingNextPage, error, status, hasNextPage, fetchNextPage, } = useInfiniteQuery( ["recipes", query], ({ pageParam = "" }) => getRecipes(pageParam), { // 增加可选链,无下一页时返回undefined,hasNextPage会自动设为false getNextPageParam: (lastPage) => lastPage._links.next?.href, } ); useEffect(() => { // 增加边界判断,只有符合条件才触发下一页加载 if (inView && hasNextPage && !isFetchingNextPage) { fetchNextPage(); } }, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
后续渲染全量食谱时,遍历data.pages拼接每一页的hits字段即可。
内容的提问来源于stack exchange,提问作者ivanatias
相关产品推荐
相关产品推荐

