NodeJS 添加无限加载到我的react应用程序导致从数据库中提取帖子,如重复循环

anauzrmj  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(227)

你好我有问题在我的mern堆栈应用程序
首先,我将limit和skip值添加到后端节点js中,如下所示

const getPosts = async (req, res) => {
  const { userId } = req.params;
  const limitValue = req.query.limit || 10;
  const skipValue = req.query.skip || 0;
  const posts = await Post.find(userId ? { bookmarks: userId } : {})
    .sort({ createdAt: -1 })
    .populate("author")
    .populate("tags")
     .limit(limitValue)
     .skip(skipValue)

  if (!posts) res.status(204).json("No posts found");
  else {
    res.status(200).json(posts.map((post) => post.toObject({ getters: true })));
  }
};

然后我进入我的react应用程序并添加了无限滚动。但类似下面的代码
但是有一个问题.它只是循环前10个职位从数据库而不是获取新职位从数据库
这是我的React代码

const PostsList = ({  filteredTag, toInvalidate, enableImages = true }) => {
  const advertise =async () => {
    
    window?.EventBus?.emit('reset-ads')
    
  }
   useEffect(() => {
   advertise()
  }, []);






  const [posts, setArticles] = useState(null);

  useEffect(() => {
    const fetchAgain = async () => {
      if (posts != null) {
        // await fetch(`${process.env.BASE_URL}/posts?skip=10`)
        await fetch("http://127.0.0.1:5000/posts?skip=10")
        .then((res) => res.json())
          .then((result) => setArticles([...posts, ...result]));
      }
    };

    const handleScroll = () => {
      const html = document.documentElement;
      const body = document.body;
      const windowheight =
        "innerHeight" in window ? window.innerHeight : html.offsetHeight;

      const docHeight = Math.max(
        body.scrollHeight,
        body.offsetHeight,
        html.clientHeight,
        html.scrollHeight,
        html.offsetHeight
      );

      const windowBottom = windowheight + window.pageYOffset;
      if (windowBottom >= docHeight) {
        console.log("we reached the bottom");
        fetchAgain();
      }
    };

    window.addEventListener("scroll", handleScroll);

    return () => window.removeEventListener("scroll", handleScroll);
  }, [posts]);

  useEffect(() => {
    setTimeout(async () => {
      // const res = await fetch(`${process.env.BASE_URL}/posts`)
      const res = await fetch("http://127.0.0.1:5000/posts")
      const data = await res.json();

      setArticles(data);
      console.log(data);
    }, 2000);
  }, []);









  


  return (
    <Wrapper>
       {posts?.length > 0 ? (
        posts.map((post, i) => (
         <><><Post
            post={post}

            isFirstPost={enableImages &&  i++}
            filteredTag={filteredTag}
            key={nanoid()}
            toInvalidate={toInvalidate} />
            <Advertise />
            </></>
        ))
      ) :
      <LoadingSpinner />
      // (
        
      //   <Placeholder />
        
      // )
      }        
    </Wrapper>
  );
};

如果可能的话,有人回答我,我尝试了每一个解决方案。它只是无限滚动工作。但不获取新的职位后,第一个10后
我不明白为什么会发生这种情况,因为后端代码或我的React代码不工作

6psbrbz9

6psbrbz91#

发生错误的原因是您的数据库查询,因为您的查询首先找到结果,然后将结果的大小限制为limit,然后根据skip大小跳过结果的前几个值。

const getPosts = async (req, res) => {
  const { userId } = req.params;
  const limitValue = req.query.limit || 10;
  const skipValue = req.query.skip || 0;
  const posts = await Post.find(userId ? { bookmarks: userId } : {})
    .sort({ createdAt: -1 })
    .populate("author")
    .populate("tags")
     .skip(skipValue) //this should be above
     .limit(limitValue) //after skipping
     

  if (!posts) res.status(204).json("No posts found");
  else {
    res.status(200).json(posts.map((post) => post.toObject({ getters: true })));
  }
};

另外,在您的前端代码中,这部分需要更正

useEffect(() => {
    const fetchAgain = async () => {
      if (posts != null) {
        // await fetch(`${process.env.BASE_URL}/posts?skip=10`)
        await fetch("http://127.0.0.1:5000/posts?skip=10")
        .then((res) => res.json())
          .then((result) => setArticles([...posts, ...result]));
      }
    };

因为skip的瓦尔是固定的,所以它只会循环前10个post。

var skip = 10;
useEffect(() => {
    const fetchAgain = async () => {
      if (posts != null) {
        // await fetch(`${process.env.BASE_URL}/posts?skip=10`)
        await fetch(`http://127.0.0.1:5000/posts?skip=${skip}`)
        .then((res) => res.json())
          .then((result) => { 
             setArticles([...posts, ...result]) 
             skip += 10
          });
      }
    };

这里skip是上面定义的值,以10开始。此外,这段代码需要一些更多的工作,删除样板代码,但要做到这一点,我需要完整的代码。
这部分更多的是一个建议,因为你可以使用IntersectionObserver来改进抓取系统,就像我也用过这个一样。要了解更多关于它的信息,你可以在youtube上搜索有一些很棒的视频。

相关问题