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

时间:2021-03-01 21:26:05

标签: javascript reactjs next.js markdown remarkjs

我收到此错误

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
  }

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

也许您可以使用以下解决方法来绕过此问题:

export const getStaticProps = async (ctx) => {
const remarkBody = await getPropsFromAService()

return { props: JSON.parse(JSON.stringify(remarkBody)) }
}

答案 1 :(得分:0)

您不能在从 undefined 返回的 props 中传递 getStaticProps。相反,您可以尝试在发生这种情况时默认为 null

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