next.js 服务器错误,序列化“getServerSideProps”时出错

hwamh0ep  于 2023-02-19  发布在  其他
关注(0)|答案(1)|浏览(206)

我的控制台显示我的发球有问题,我无法解决:

Uncaught Error: Error serializing .title returned from getServerSideProps in "/property/[slug]".
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.

我正在使用sanity和next.js
这是我从slug组件中得到的代码:

export const getServerSideProps = async (pageContext) => {
  const pageSlug = pageContext.query.slug

  const query = `*[-type == "property" && slug.current == $pageSlug][0]{
    title,
    location,
    propertyType,
    mainImage,
    images,
    pricePerNight,
    beds,
    bedrooms,
    description,
    host->{
      _id,
      name,
      slug,
      image
    },
    reviews[]{
      ...,
      traveller->{
        _id,
        name,
        slug,
        image
      }
    }
  }`

  const property = await sanityClient.fetch(query, { pageSlug})

  if (!property) {
    return {
      props: null,
      notFound: true,
    }
  } else {
    return {
      props: {
        title: property.title,
        location: property.location,
        propertyType: property.propertyType,
        mainImage: property.mainImage,
        images: property.images,
        pricePerNight: property.pricePerNight,
        beds: property.beds,
        bedrooms: property.bedrooms,
        description: property.description,
        host: property.host,
        reviews: property.reviews
      }
    }
  }
}

export default Property

在我的终端中,客户端和服务器端编译成功.
我尝试返回JSON.stringify,但仍然没有成功。

of1yzvn4

of1yzvn41#

根据Next.js文档,props对象应该是可序列化的,以便您的呈现站点正确获取。undefined值(就像函数一样)是不可序列化的。
您可以为 prop 提供null回退值,这些值可以是undefined

export const getServerSideProps = () => {
  // some fetching logic
  return {
    props: {
      title: property.title || null
      // rest of props
    }
  }; 
}

相关问题