为什么我的Next.js Route无限加载?

i7uaboj4  于 2023-02-04  发布在  其他
关注(0)|答案(2)|浏览(211)

我正试图建立一个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;
mspsb9vt

mspsb9vt1#

乍一看,这似乎是正确的。如果你添加控制台日志到getStaticPropsgetStaticPaths,你会看到他们在构建时。
您应该看到getStaticPaths被调用一次,然后getStaticProps为getStaticProps返回的每个路径调用一次。
如果你的页面是无限加载的,看看这个页面的react组件,试着把它简化成console.log,你得到的 prop ,和“hello world”。
您可能有一个useEffect(或其他钩子),它依赖于在钩子内更新的状态,从而导致无限循环。

eni9jsuy

eni9jsuy2#

首先,在 next.config.js 文件中将reactStrictMode设置为true,以防止无限渲染:

module.exports = {
  reactStrictMode: true,
};

然后在您的useEffect中验证,您很可能正在更新从属关系数组中的hook,并且它应该是objectarray,如下所示:

const [test, setTest] = useState({}); // maybe an array
//...
useEffect(() => {
  //...
  const newValue = {first: "valueOfFirst", second: "valueOfSecond"};
  setTest(newValue);
}, [test]);

这将导致一个无限的渲染因为两个对象或两个数组总是不相等.如果是这样的话,一种方法来修复它是比较的JSON.stringify的prev值和下一个:

setTest((prev) => {
  if (!JSON.stringify(prev) === JSON.stringify(newValue)) return newValue;
});

相关问题