无限滚动在next js中不起作用,相同的代码在普通create-react-app上起作用
next js
create-react-app
rqdpfwrv1#
与普通的React Js不同,NextJs中的无限滚动有不同的方法。这里我们将使用一个名为react-infinite-scroll-component的npm包。让我们看看index.js文件index.js
React Js
NextJs
react-infinite-scroll-component
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
getStaticProps
json data as props
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
1条答案
按热度按时间rqdpfwrv1#
与普通的
React Js
不同,NextJs
中的无限滚动有不同的方法。这里我们将使用一个名为react-infinite-scroll-component
的npm包。让我们看看
index.js
文件index.js
在上面的代码中,你可以看到我们正在从
getStaticProps
获取数据,它返回json data as props
,我们正在接收该prop并将其传递给组件。如果你仔细观察,我们将初始渲染限制为10
,所以,前10个数据将被显示,然后我们将再次从服务器获取data
。现在,让我们看看内容页
Content.js
这里我们从服务器获取更多的帖子,在所有的数据加载之后。代码是不言自明的。
在上面的状态下,我们将前面的数据附加到传入的数据中
您可以检查此代码沙箱,以了解其实际工作方式。
https://codesandbox.io/s/next-js-infinite-scroll-3vfem