【发布时间】:2022-06-16 17:48:46
【问题描述】:
我是 reactjs 的新手。我在stackoverflow上发现了关于这个主题的几个问题,也搜索了谷歌,但现在我仍然无法实现无限滚动。我几乎从昨天开始为实现无限滚动而苦苦挣扎。
我使用 django rest 来构建我的 api。这是我的 api 调用如下所示:
我的 api 网址: http://127.0.0.1:8000/blog-api/?limit=2
{
"count": 6,
"next": "http://127.0.0.1:8000/blog-api/?limit=2&offset=2",
"previous": null,
"results": [
{
"id": 4,
"blog_title": "Blog1",
"blog_body": "hello",
"blog_header_image": "https://d2ofoaxmq8b811.cloudfront.net/media/Capture_46syzro.PNG",
"author": 1
},
{
"id": 5,
"blog_title": "blog2",
"blog_body": "hello2",
"blog_header_image": "https://d2ofoaxmq8b811.cloudfront.net/media/Capture1.PNG",
"author": 4
}
]
}
这是我的 nextjs 代码,目前在我的页面中显示 2 个项目,但我还想在滚动时加载更多数据:
const Blog = ({ content }) => {
return (
{content.results.map((data) => (
<h1>{data.blog_title}</h1>
))}
)}
这里我使用的是 getServerSideProps 函数。
export async function getServerSideProps() {
// Fetch data from external API
const url = "http://127.0.0.1:8000/blog-api?limit=2";
const headers = {
method: "GET",
"Content-Type": "application/json",
Accept: "application/json",
"User-Agent": "*",
Authorization: "Token <>",
};
const res = await fetch(url, { headers: headers });
const data = await res.json();
console.log(data);
// Pass data to the page via props
return {
props: {
content: data,
},
};
}
我也尝试了 react-infinite-scroll-component 并阅读了他们的文档,但无法应用无限滚动。
【问题讨论】:
标签: javascript reactjs next.js