我正在使用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,
},
};
};正如您在这张图片中所看到的,它正在获取和打印内容。

但是,当我通过时,我会得到以下错误:将它作为道具传递
Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.发布于 2021-12-22 12:43:48
看来,出于性能原因,nextJS不喜欢序列化任何东西,只喜欢标量类型。您可以在此github问题中阅读更多内容。处理此问题的最佳方法是在返回日期对象之前将日期对象转换为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);发布于 2022-07-02 07:25:54
如果使用的是类型记录,则不能将createdAt类型更改为字符串或数字,如下所示:
newsLetter.createdAt = newsLetter.createdAt.toString();
// Error: Type 'string' is not assignable to type 'Date'.相反,您可以使用JOSN.stringfy在JSON.parse中创建一个可序列化的对象:
export const getStaticProps = async () => {
const prisma = new PrismaClient();
const newsLetters = await prisma.newsLetters.findMany();
return {
props: {
newsLetters: JSON.parse(JSON.stringify(newsLetters)) // <===
}
}
}发布于 2022-03-31 18:49:01
根据NextJS API文档,getStaticProps返回“应该是一个可序列化的对象,以便传递的任何道具都可以用JSON.stringify序列化。”
在它们允许的遮罩下,布尔值、数字、字符串和任何通过Lodash isPlainObject测试的内容。https://lodash.com/docs/#isPlainObjectChecks。在这个函数的Lodash文档中,它声称“检查值是否是一个普通对象,即由对象构造函数创建的对象,还是一个[原型]为null的对象。
下面的堆栈文章讨论了两者之间的区别。JavaScript中对象与普通对象的区别?
构建在@Viktor回答之上,取决于您从道具中需要什么,您只需将其转换为字符串、数字或Lodash的isPlainObject接受的其他类型。
对于我来说,我有一个通过Prisma提供的日期对象,就像OP一样,我只是把它转换成类似这样的字符串。
for (const element of newsLetters) {
element.createdAt = element.createdAt.toString()
}https://stackoverflow.com/questions/70449092
复制相似问题