next.js 如何在下一个js中实现无限滚动?

jrcvhitl  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(171)

无限滚动在next js中不起作用,相同的代码在普通create-react-app上起作用

rqdpfwrv

rqdpfwrv1#

与普通的React Js不同,NextJs中的无限滚动有不同的方法。这里我们将使用一个名为react-infinite-scroll-component的npm包。
让我们看看index.js文件index.js

import Content from "./Content";

export default function index(props) {
  return (
    <>
      <div>
        <Content data={props.data} />
      </div>
    </>
  );
}

export const getStaticProps = async () => {
  const data = await fetch(
    "https://jsonplaceholder.typicode.com/todos?_limit=10"
  ).then((response) => response.json());
  return {
    props: { data }
  };
};

在上面的代码中,你可以看到我们正在从getStaticProps获取数据,它返回json data as props,我们正在接收该prop并将其传递给组件。如果你仔细观察,我们将初始渲染限制为10,所以,前10个数据将被显示,然后我们将再次从服务器获取data
现在,让我们看看内容页Content.js

import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

const Content = ({ data }) => {
  const [posts, setPosts] = useState(data);
  const [hasMore, setHasMore] = useState(true);

  const getMorePost = async () => {
    const res = await fetch(
      `https://jsonplaceholder.typicode.com/todos?_start=${posts.length}&_limit=10`
    );
    const newPosts = await res.json();
    setPosts((post) => [...post, ...newPosts]);
  };

  return (
    <>
      <InfiniteScroll
        dataLength={posts.length}
        next={getMorePost}
        hasMore={hasMore}
        loader={<h3> Loading...</h3>}
        endMessage={<h4>Nothing more to show</h4>}
      >
        {posts.map((data) => (
          <div key={data.id}>
            <div className="back">
              <strong> {data.id}</strong> {data.title}
            </div>
            {data.completed}
          </div>
        ))}
      </InfiniteScroll>
      <style jsx>
        {`
          .back {
            padding: 10px;
            background-color: dodgerblue;
            color: white;
            margin: 10px;
          }
        `}
      </style>
    </>
  );
};

export default Content;

这里我们从服务器获取更多的帖子,在所有的数据加载之后。代码是不言自明的。

setPosts((post) => [...post, ...newPosts]);

在上面的状态下,我们将前面的数据附加到传入的数据中
您可以检查此代码沙箱,以了解其实际工作方式。
https://codesandbox.io/s/next-js-infinite-scroll-3vfem

相关问题