next.js 正在生成静态页面(0/8)类型错误:无法析构“post”的属性“title”,因为它未定义

vdzxcuhz  于 2022-12-18  发布在  其他
关注(0)|答案(3)|浏览(102)

我正在用nextJS & sanity开发一个博客。我把sanity和nextJS连接起来,它在开发模式下工作得很好。但是当我试图在Vercel中部署或通过VSCode构建时,它显示了下面的错误。

info  - Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined.

下面是我的组件概述

export default function SinglePost({ post }) {
  const {
    title,
    imageUrl,
    publishedAt,
    description,
    topics,
    rescources,
    sourcecode,
    body = [],
  } = post;
return(
<div>
    <h1>{title}</h1>
    //remaining code....
</div>)
}
const query = groq`*[_type == "post" && slug.current == $slug][0]{
  "title": title,
  "imageUrl": mainImage.asset->url,
  description,
  "topics": topics[],
  "rescources": rescources[],
  "sourcecode": sourcecode,
  "publishedAt": publishedAt,
  body,
  
}`;

export async function getStaticPaths() {
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)][].slug.current`
  );

  return {
    paths: paths.map((slug) => ({ params: { slug } })),
    fallback: true,
  };
}

export async function getStaticProps(context) {
 
  const { slug = "" } = context.params;
  const post = await client.fetch(query, { slug });
  return {
    props: {
      post,
    },
  };
}
k4ymrczo

k4ymrczo1#

嗨,我发现这个工作

const Page: NextPage = (props: any) => {
      const { post = undefined || {} } = props
      const { title = "Undefined title" } = post
      return (
        <>
          <Head>
            <title>{title}</title>
          </Head>
        </>
      )
    }
const query = groq`*[_type == "post" && slug.current == $slug][0]{
      title,
      "name": author->name,
      "authorImage": author->image,
      "categories": categories[]->title,
    }`
    
    export async function getStaticProps(context: any) {
      // It's important to default the slug so that it doesn't return "undefined"
      const { slug = '' } = context.params
      const post = await client.fetch(query, { slug })
      return {
        props: {
          post,
        },
      }
    }
j2datikz

j2datikz2#

我能够解决这个问题。
解决方案:不对“title”进行结构化,而是通过直接访问得到一个值

<h1>{post.title}</h1>
x4shl7ld

x4shl7ld3#

我遇到了同样的问题,错误显示为prerender-error,我添加了一个if块来处理回退:

const PostId = ({postId}) => {

    const router = useRouter()

    if (router.isFallback) {
        return <div>Loading...</div>
    }
    return (
       ...
    )
...
}

并且成功生成,请确保在第页中处理回退

相关问题