如何使用响应数据作为 useInfiniteQuery 的选项

how to use response data as options for useInfiniteQuery

在我想使用 useInfiniteQuery 的页面中

 const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery(
    ['posts', searchState],
    ({ pageParam = 1 }) => post.search({ ...searchState, pageParam }),
    {
      getNextPageParam: (lastPage, pages) => {
        if (pages.length < 2) return pages.length + 1;
        else return undefined;
      },
    },
  );

这是我自定义的 axios 函数:

export const post = {
 search: async (params: { keyword: string; sort: string; region: string; pageParam: number }) => {
    const { keyword, sort, region, pageParam } = params;
    const sortValue = SortType[sort as keyof typeof SortType];
    const url = `/post/search?keyword=${keyword}&page=${pageParam}&filter=${sortValue}&region=${region}`;
    console.log(url);
    const res = await client.get(url);
    return res;
  },
}

res in post.search 函数 returns:

{"status":200,"message":"search success","data":{"posts":[],"pageCount":0}}

并且我想使用 pageCount 作为 getNextPageParam 函数 hasNextPage 值的条件。

我真正想问的是,如何在以下代码中使用 pageCount 值:

getNextPageParam: (lastPage, pages) => {

对于不习惯使用 react-query 的人。 您可以使用 lastPage

简单地查找 res.data
  const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery(
    ['posts', searchState],
    async ({ pageParam = 1 }) => (await post.search({ searchState, pageParam })).data,
    {
      getNextPageParam: (lastPage, allPages) => {
        if (lastPage === undefined) return undefined;
        else return allPages.length < lastPage.pageCount && allPages.length + 1;
      },
    },
  );