首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成静态页面(0/8)TypeError:无法构造“post”的属性“title”,因为它是未定义的

生成静态页面(0/8)TypeError:无法构造“post”的属性“title”,因为它是未定义的
EN

Stack Overflow用户
提问于 2022-09-14 13:15:45
回答 2查看 80关注 0票数 1

我正在使用nextJS & sanity开发一个博客。我把理智与nextJS连接起来,它在开发模式下完美地工作着。但是,当我尝试在Vercel中部署或通过VSCode构建时,它将显示以下错误。

代码语言:javascript
复制
info  - Generating static pages (0/8)TypeError: Cannot destructure property 'title' of 'post' as it is undefined.

这是我的组件概述

代码语言:javascript
复制
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,
    },
  };
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-20 22:12:11

我解决了这个问题。

解决方案:在不破坏“标题”的情况下,我通过直接访问获得了一个值。

代码语言:javascript
复制
<h1>{post.title}</h1>
票数 0
EN

Stack Overflow用户

发布于 2022-09-16 14:01:42

嗨,我发现这个很管用

代码语言:javascript
复制
    const Page: NextPage = (props: any) => {
      const { post = undefined || {} } = props
      const { title = "Undefined title" } = post
      return (
        <>
          <Head>
            <title>{title}</title>
          </Head>
        </>
      )
    }
代码语言:javascript
复制
       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,
        },
      }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73717526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档