原因:`object` ("[object Date]") 无法序列化为 JSON。请仅 return JSON 可序列化数据类型

Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types

我正在使用 prisma 和 Next.js。当我尝试从 getStaticProps 中的 prisma 检索内容时,它确实获取了数据,但我无法将其传递给主要组件。

export const getStaticProps = async () => {
  const prisma = new PrismaClient();
  const newsLetters = await prisma.newsLetters.findMany();
  console.log(newsLetters);

  return {
    props: {
      newsLetters: newsLetters,
    },
  };
};

正如您在此图像中看到的,它正在获取和打印内容。

但是当我通过时,将其作为 props 传递时出现以下错误

Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.

看起来 nextJS 出于性能原因不喜欢序列化标量类型以外的任何东西。您可以在此 github issue 中阅读更多内容。处理此问题的最佳方法是在返回 Date 对象之前将它们转换为 UNIX 时间戳。

// your data
let newsLetters = [
    {
        id: 'your-id',
        email: 'email@example.com',
        createdAt: new Date()
    }
];

// map the array
newsLetters.map(x => {
    x.createdAt = Math.floor(x.createdAt / 1000);
    return x;
})

// use newsLetters now
console.log(newsLetters);

根据 NextJS API 文档 getStaticProps return“应该是一个可序列化的对象,这样传递的任何道具都可以用 JSON.stringify 序列化。”

在幕后他们允许布尔值、数字、字符串和任何通过 Lodash isPlainObject 测试的东西。 https://lodash.com/docs/#isPlainObjectChecks。 在这个函数的 Lodash 文档中,它声称“检查值是否是普通对象,即由对象构造函数创建的对象或 [[Prototype]] 为 null 的对象。”

以下堆栈 post 讨论了差异。

基于@Viktor Kynchev 的回答,根据您对道具的需求,您可以将其转换为字符串、数字或 Lodash 的 isPlainObject 接受的其他类型。

对我来说,我有一个通过 Prisma API 提供的日期对象,就像 OP 一样,我只是将它转换为字符串。

for (const element of newsLetters) {
  element.createdAt = element.createdAt.toString()
}