next.js TypeError:无法读取未定义(类型)的属性

alen0pnh  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(186)

我有一个基于NextJs的前端和基于strapi cms的后端的项目。我有一个名为blog的集合类型来在我的网站上发布blog。我已经添加了blog和所有必要的字段,但是blog显示:TypeError: Cannot read properties of undefined type。API没有问题,因为我正在获取该博客的完整对象。由于某种原因,它没有获取博客。我以前添加了许多博客,这些博客都在工作,但现在当我试图添加一个新的博客时,我得到了这个错误,然后在大约30分钟后,我得到了一个404页面。
下面是blogs/[slug].js文件:

import { useEffect } from "react";
import { fetchAPI, updateViews } from "../../utils/api";
import InsightsSinglePageLayout from "@/components/elements/insights-single-layout";

const Blog = ({ blog, similarBlogs }) => {

  useEffect(() => {
    // Update the views count
    fetchAPI(`/blogs?slug=${blog.slug}`)
      .then((latestBlog) => {
          updateViews("blogs", latestBlog[0]);
      });

  }, []);

  return (
    <section>
        <InsightsSinglePageLayout insightsData = {blog}
                                  similarInsight = {similarBlogs}
                                  type={blog.type.title.toLowerCase()}/>
    </section>
  ) 
};

export const getStaticProps = async (context) => {
  const blog = await fetchAPI(`/blogs?slug=${context.params.slug}`)
  const similarBlogs = await fetchAPI(`/solutions?title=${blog[0].solution?.title}`)

  return {
    props: {
      blog : blog[0],
      similarBlogs : similarBlogs[0] ? similarBlogs[0].blogs.filter(data => data.id != blog[0].id).slice(0,5) : [] ,
    },
  };
};
export const getStaticPaths = async () => {
  const blogs = await fetchAPI('/blogs')
  const slugs = blogs.map(blog => blog.slug)
  const paths = slugs.map(slug => ( {params : { slug : slug.toString() }} ))
  return{
      paths,
      fallback:false
  }
};
export default Blog;

我已经重新启动了临时服务器,希望得到一个更好的错误,并尝试调试它,但我得到了同样的错误。

k5ifujac

k5ifujac1#

可能在初始加载中为blog获取空值

{blog&& <InsightsSinglePageLayout insightsData = {blog}
                                  similarInsight = {similarBlogs}
                                  type={blog.type.title.toLowerCase()}/>
}

相关问题