使用 getStaticProps 序列化时出错 - nextjs

时间:2021-06-08 17:04:33

标签: javascript next.js

这是我的 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.

1 个答案:

答案 0 :(得分: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,
    },
  }
}

希望有帮助!