反应查询:useInfiniteQuery

React-Query: useInfiniteQuery

所以,我已经查看了此处的文档和答案,但我仍然需要一些帮助:

index.tsx

const getInfiniteArticles = ({ pageParams = 0 }) => {
  const res = await axios.get('/api/articles', { params: { page: pageParams } });

  return res.data;
}

api/articles.ts

const getArticles = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    const { page } = req.query;
    const pageNum = Number(page);

    const data = await NewsService.getArticles(getRange(pageNum));

    return res.status(200).json({
      data,
      previousPage: pageNum > 0 ? (pageNum - 1) : null,
      nextPage: pageNum + 1,
    });
  } catch (err) {
    res.json(err);
    res.status(405).end();
  }
};

export default getArticles;

index.tsx

  const { data: articlePages, fetchNextPage } = useInfiniteQuery(
    'infinite-articles', 
    getInfiniteArticles, 
    {
      getNextPageParam: (lastPage, allGroups) => {
        console.log('lastPage: ', lastPage);
        console.log('allGroups: ', allGroups);
        return lastPage.nextPage;
      }
    });

  const handleLoadMore = () => {
    fetchNextPage();
  };

点击下一页后的控制台:

lastPage: { data: Array(50), previousPage: null, nextPage: 1}
allGroups: [
{ data: Array(50), previousPage: null, nextPage: 1},
{ data: Array(50), previousPage: null, nextPage: 1},
]

感谢任何关于为什么我得到相同组的帮助! :)

所以,事实证明我的结构不正确

 const {
   fetchNextPage,
   fetchPreviousPage,
   hasNextPage,
   hasPreviousPage,
   isFetchingNextPage,
   isFetchingPreviousPage,
   ...result
 } = useInfiniteQuery(queryKey, ({ pageParam = 1 }) => fetchPage(pageParam), {
   ...options,
   getNextPageParam: (lastPage, allPages) => lastPage.nextCursor,
   getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,
 })
queryFn: (context: QueryFunctionContext) => Promise<TData>

queryFn 应该是 returns Promise

的同步函数

我要么传递异步函数,要么返回 TData 而不是承诺。

更新和工作:

  const getInfiniteArticles = ({ pageParam = 0 }) => axios.get('/api/articles', { params: { page: pageParam } });
  const { data: articlePages, fetchNextPage } = useInfiniteQuery('articles', getInfiniteArticles, {
    getNextPageParam: (lastPage, pages) => {
      // the returned axios response
      return lastPage.data.nextPage;
    }
  });

Reference Page