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



next js中的无限滚动不起作用,相同的代码适用于正常create-react-app

与普通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

最新更新