【问题标题】:Error serializing with getStaticProps - nextjs使用 getStaticProps 序列化时出错 - nextjs
【发布时间】:2021-08-25 17:07:06
【问题描述】:

这是我的 getTopGifts 函数:

export async function getTopGifts() {
const data = [{"id":1,"title":"test"}]

return data
}

但是当我使用上面的函数时出现错误:

export async function getStaticProps() {
  // fetch list of gifts
  const gifts = getTopGifts()
  console.log(typeof(_gifts))
  return {
    props: {
      gifts: gifts
    },
  }
}

我的错误:

Error: Error serializing `.gifts` returned from `getStaticProps` in "/gifts".
Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

【问题讨论】:

    标签: javascript next.js


    【解决方案1】:

    您将getTopGifts 设为async 函数,尝试使用await 解析getTopGifts 的值。如果没有await,这是一个未决的承诺:

    export async function getStaticProps() {
      // fetch list of gifts
      const gifts = await getTopGifts()
      console.log(typeof(gifts));
      return {
        props: {
          gifts,
        },
      }
    }
    

    希望对您有所帮助!

    【讨论】:

    • 我被这个问题困扰了很久......试图修复被调用的函数返回一个 Promise 但实际上这只是因为 getStaticProps() 在调用它时没有“等待”......所以它不是......等待:)
    猜你喜欢
    • 2021-08-06
    • 2021-06-22
    • 2021-06-19
    • 2020-11-05
    • 2022-10-22
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多