我正试图建立一个Next.js简单的博客与Strapi。
我尝试设置动态路由,这样当用户访问localhost:3000/blog/blog-name时,它会获得正确的数据并呈现它。但是到目前为止,我的应用程序所做的一切都是无限加载,我不知道为什么。我甚至看不到控制台中的任何错误,因为无限加载。
例如,我正在尝试访问博客ID 1,如果我点击端点localhost:1337/api/blogs/1
,我会得到以下响应:
{
"data": {
"id": 1,
"attributes": {
"title": "Testing Blog",
"slug": "testing-blog",
"createdAt": "2023-02-03T17:03:30.626Z",
"updatedAt": "2023-02-03T17:03:32.666Z",
"publishedAt": "2023-02-03T17:03:32.664Z"
}
},
"meta": {}
}
如果我点击localhost:1337/api/blogs,我会得到以下内容:
{
"data": [
{
"id": 1,
"attributes": {
"title": "Testing Blog",
"slug": "testing-blog",
"createdAt": "2023-02-03T17:03:30.626Z",
"updatedAt": "2023-02-03T17:03:32.666Z",
"publishedAt": "2023-02-03T17:03:32.664Z"
}
},
{
"id": 2,
"attributes": {
"title": "Testing Blog 2",
"slug": "testing-blog-2",
"createdAt": "2023-02-03T17:16:40.923Z",
"updatedAt": "2023-02-03T17:16:41.387Z",
"publishedAt": "2023-02-03T17:16:41.385Z"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 2
}
}
}
下面是我的代码
文件:/pages/blog/[slug].js
代码:
import axios from "axios";
import React, { useEffect } from "react";
const Blog = (props) => {
return (
<>
<h1>TESTING</h1>
</>
);
};
export async function getStaticProps({ params }) {
const res = await axios.get(`http://localhost:1337/api/blogs/1`);
return {
props: {
content: res.data.data,
},
};
}
export async function getStaticPaths() {
const res = await axios.get("http://localhost:1337/api/blog");
const blogs = res.data.data;
console.log("blogs", blogs);
const paths = blogs.map((blog) => {
return {
params: {
id: blog.id,
},
};
});
return {
paths,
fallback: true,
};
}
export default Blog;
2条答案
按热度按时间mspsb9vt1#
乍一看,这似乎是正确的。如果你添加控制台日志到
getStaticProps
和getStaticPaths
,你会看到他们在构建时。您应该看到getStaticPaths被调用一次,然后getStaticProps为getStaticProps返回的每个路径调用一次。
如果你的页面是无限加载的,看看这个页面的react组件,试着把它简化成console.log,你得到的 prop ,和“hello world”。
您可能有一个useEffect(或其他钩子),它依赖于在钩子内更新的状态,从而导致无限循环。
eni9jsuy2#
首先,在 next.config.js 文件中将
reactStrictMode
设置为true
,以防止无限渲染:然后在您的
useEffect
中验证,您很可能正在更新从属关系数组中的hook
,并且它应该是object
或array
,如下所示:这将导致一个无限的渲染因为两个对象或两个数组总是不相等.如果是这样的话,一种方法来修复它是比较的
JSON.stringify
的prev值和下一个: