我想单击“加载更多”底部并获取 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
用于获取用于第一次渲染的数据。与此不同的是,您的“加载更多”按钮需要在客户端工作。
我将尝试总结您应该采取的步骤:
为了能够操作将显示的帖子,您需要将项目存储在状态中,而不是道具中。因此,使用useState
来自 props 的数据创建一个状态并填充它,如下所示:
const [posts, setPosts] = useState(props.posts);
Run Code Online (Sandbox Code Playgroud)
从现在开始,您将使用此posts
变量而不是 props 中的变量。
添加“加载更多”按钮。所有加载更多帖子的业务逻辑都应该转到其onClick
处理程序。像这样的东西:
<button
onClick={async () => {
const newPosts = await getNewPostsFromApi();
setPosts(...posts, ...newPosts);
}}
type="button"
>
Load more
</button>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9488 次 |
最近记录: |