序列化从`getStaticProps`返回的`.markBody`时出错。原因:`unfined`不能序列化为JSON

我收到此错误

Error: Error serializing `.remarkBody` returned from `getStaticProps` in "/blog/[slug]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

尝试运行此程序时:

const body = blogPostCollection ? blogPostCollection?.items[0]?.body : ''

  const remarkBody = remark().use(strip).process(body, (err, file) => {
    if (err) throw err
    String(file)
  })

  return {
    props: {
      remarkBody: remarkBody,
    },
    revalidate: 1
  }

有人能帮我吗?


解决方案

无法传入undefinedgetStaticProps返回的props。相反,您可以在发生这种情况时尝试默认到null

return {
    props: {
        remarkBody: remarkBody ?? null,
    },
    revalidate: 1
}

相关文章