【问题标题】:Error serializing `.remarkBody` returned from `getStaticProps` . Reason: `undefined` cannot be serialized as JSON序列化从 `getStaticProps` 返回的 `.remarkBody` 时出错。原因:`undefined` 不能序列化为 JSON
【发布时间】:2021-03-02 20:35:38
【问题描述】:

我收到了这个错误

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
  }

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: javascript reactjs next.js markdown remarkjs


    【解决方案1】:

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

    export const getStaticProps = async (ctx) => {
    const remarkBody = await getPropsFromAService()
    
    return { props: JSON.parse(JSON.stringify(remarkBody)) }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-25
        • 2021-08-06
        • 2021-04-23
        • 2023-03-06
        • 2021-06-22
        • 2021-08-25
        • 1970-01-01
        • 2022-01-23
        • 2022-10-03
        相关资源
        最近更新 更多