如何在 nextjs 中创建加载更多底部以获取其余数据?(Next.js 分页)

ham*_*ami 6 reactjs next.js

我想单击“加载更多”底部并获取 next.js 中的其余数据,如何做到这一点?在此页面中,我用来getServerSideProps从 api 获取数据

我的页面代码是:

export default function Posts({ posts, popular }) {
  const classes = useStyles();
  return (
    <motion.main
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
    >
      <InnerWrapper pbNone>
        <Title title="Latest Post" subTitle />
      </InnerWrapper>
      <HeroSection data={posts} />
      <InnerWrapper>
        <Grid container spacing={3}>
          <Grid item xs={12} sm={8}>
            {posts.map(item => (
              <HorizontalCard key={item.id} info={item} />
            ))}

            <LoadMoreBtn />
            
          </Grid>
          <Grid item xs={12} sm={4}>
            <div className={classes.marginBottom}>
              <Title title={"Most Popular"} subTitle side={true} />
              <SideList data={popular} />
            </div>
            <div className={classes.marginBottom}>
              <SubscribeSide />
            </div>
          </Grid>
        </Grid>
      </InnerWrapper>
    </motion.main>
  );
}

export const getServerSideProps = async ({ query }) => {
  // Fetch data from external API
  const { data: posts } = await postLists(0);
  const { data: popular } = await popularPost();
  // Pass data to the page via props
  return { props: { posts, popular } };
};
Run Code Online (Sandbox Code Playgroud)

Gok*_*ari 11

getServerSideProps用于获取用于第一次渲染的数据。与此不同的是,您的“加载更多”按钮需要在客户端工作。

我将尝试总结您应该采取的步骤:

  1. 为了能够操作将显示的帖子,您需要将项目存储在状态中,而不是道具中。因此,使用useState来自 props 的数据创建一个状态并填充它,如下所示:

    const [posts, setPosts] = useState(props.posts);
    
    Run Code Online (Sandbox Code Playgroud)

    从现在开始,您将使用此posts变量而不是 props 中的变量。

  2. 添加“加载更多”按钮。所有加载更多帖子的业务逻辑都应该转到其onClick处理程序。像这样的东西:

    <button
      onClick={async () => {
         const newPosts = await getNewPostsFromApi();
    
         setPosts(...posts, ...newPosts);
      }}
      type="button"
    >
    Load more
    </button>
    
    Run Code Online (Sandbox Code Playgroud)

  • UPD:刚刚发现网站将“&amp;page=2”添加到查询参数中,即使对于无限滚动列表或带有“显示更多”按钮的列表也是如此。所以不需要 `useState`:所有状态都在 url 中。 (2认同)