javascript 使用InfiniteQuery进行React的无限滚动

r3i60tvu  于 2023-02-15  发布在  Java
关注(0)|答案(1)|浏览(145)

我是react-query的新手,我在实现useInfiniteQuery函数时遇到了一些麻烦。我试着在我的网站中实现它,但是它似乎没有像它应该的那样增加pageIndex变量。pageIndex一直保持在0。因此每次获取数据时都会复制我的帖子。offset变量用于数据库获取n行,查询将从该行获取。
寻求帮助,谢谢。
以下是前端部分:

import React from "react";
import { useRef, useCallback} from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useInfiniteQuery } from "react-query";

const PAGE_LIMIT = 10;

const fetchPosts = async (key, pageIndex = 0) => {
  const offset = pageIndex * PAGE_LIMIT;
  try {
    const { data } = await axios.get(`/posts`, {
      params: { offset: offset, limit: PAGE_LIMIT },
    });
    return data;
  } catch (err) {
    console.log(err);
  }
};

const Home = () => {
  const {
    fetchNextPage,
    hasNextPage, 
    isFetchingNextPage, 
    data,
    status,
    error,
  } = useInfiniteQuery("/posts", ({ pageIndex = 0 }) => fetchPosts(pageIndex), {
    getNextPageParam: (lastPage, allPages) => {
      return lastPage.length ? allPages.length : undefined;
    },
  });

  const intObserver = useRef();
  const lastPostRef = useCallback(
    (post) => {
      if (isFetchingNextPage) return;

      if (intObserver.current) intObserver.current.disconnect();

      intObserver.current = new IntersectionObserver((posts) => {
        if (posts[0].isIntersecting && hasNextPage) {
          console.log("We are near the last post!");
          fetchNextPage();
        }
      });

      if (post) intObserver.current.observe(post);
    },
    [isFetchingNextPage, fetchNextPage, hasNextPage]
  );

  if (status === "error")
    return <p className="center">Error: {error.message}</p>;

  const content = data?.pages.map((pg) => {
    return pg.map((post, i) => {
      if (pg.length === i + 1) {
        return (
          <Link ref={lastPostRef} className="link" to={`/post/${post.id}`}>
            <div className="post" key={post.id}>
              <p> {post.title}</p>
              <p> {post.content}</p>
            </div>
          </Link>
        );
      }
      return (
        <Link className="link" to={`/post/${post.id}`}>
          <div className="post" key={post.id}>
            <p> {post.title}</p>
            <p> {post.content}</p>
          </div>
        </Link>
      );
    });
  });

  return (
    <div>
      <div className="home">
        <div className="container">
          <div className="posts">
            {content}
            {isFetchingNextPage && (
              <p className="center">Loading More Posts...</p>
            )}
            <p className="center">
              <a href="#top">Back to Top</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;

下面是后端部分:

import { db } from "../db.js";

export const getPosts = (req, res) => {
  const { offset, limit } = req.query;
  console.log(`Offset is ${offset}`);
  const q = `SELECT * FROM test1 ORDER BY ID LIMIT ?, ?`;

  db.query(q, [parseInt(offset), parseInt(limit)], (err, data) => {
    if (err) return res.status(500).json(err);

    return res.status(200).json(data);
  });
};
xfb7svmp

xfb7svmp1#

你给予useInfiniteQuery的fetch回调函数接收到一个QueryFunctionContext。它有一个名为pageParam的属性。你使用的pageIndex不在那个对象上。因为你给它一个默认值0,它将总是零。请改用pageParam

相关问题