0

我目前在尝试将无限查询功能添加到我正在使用 Edamam API 开发的食谱应用程序时遇到一些问题。

我寻找的所有示例(甚至是 React Query 的文档)都使用页面/光标编号系统实现了无限滚动……我知道这是理想的方式,但是……Edamam API 不适用于分页查询.

相反,对于我们要查找的每个食谱查询,API 具有以下结构(假设我们正在搜索“chicken”,这将是 JSON 结构):

from: 1,
to: 20,
count: 10000,
_links: {
          next: {
                  href: "https://api.edamam.com/api/recipes/v2?q=chicken&app_key=APIKEYc&_cont=CHcVQBtNNQphDmgVQntAEX4BYldtBAAGRmxGC2ERYVJ2BwoVX3cVBWQSY1EhBQcGEmNHVmMTYFEgDQQCFTNJBGQUMQZxVhFqX3cWQT1OcV9xBB8VADQWVhFCPwoxXVZEITQeVDcBaR4-SQ%3D%3D&type=public&app_id=APPID"
                 title: "Next Page"
                }
},
hits: [{}] ... (This is where the actual recipes are)

如您所见,分页查询没有编号系统,相反,它是一个完整的 URL,这让我很难过,因为我也是 React Query 的新手。

我尝试了以下方法,但是当我到达页面底部时,它只是一遍又一遍地获取相同的数据:

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();

  useEffect(() => {
    inView && fetchNextPage();
  }, [inView]);

  const {
    data,
    isFetching,
    isFetchingNextPage,
    error,
    status,
    hasNextPage,
    fetchNextPage,
  } = useInfiniteQuery(
    ["recipes", query],
    ({ pageParam = "" }) => getRecipes(pageParam),
    {
      getNextPageParam: (lastPage) => lastPage._links.next.href,
    }
  );

由于下一页参数是一个完整的 URL,我只是说如果有一个 pageParam,则使用该 URL 进行请求,如果没有,则使用用户正在搜索的查询值执行正常请求。

请帮忙!

4

1 回答 1

0

由于下一页参数是一个完整的 URL,我只是说如果有一个 pageParam,则使用该 URL 进行请求,如果没有,则使用用户正在搜索的查询值执行正常请求。

我会说这是正确的方法。我在您的示例中可以看到的唯一代码问题是您破坏了页面参数,然后将页面参数字符串传递给getRecipes

({ pageParam = "" }) => getRecipes(pageParam),

但是在 中getRecipes,您希望有一个对象进入(您再次对其进行解构):

const getRecipes = async ({ pageParam }) => {

您可以通过更改调用方或函数语法来解决此问题,然后它应该可以工作。

于 2021-10-22T18:01:49.153 回答