Next.js类组件如何遍历Prisma返回JSON并解决日期序列化问题
问题原因
- 你在
getServerSideProps中将Prisma返回的数组通过JSON.stringify转为了字符串类型,字符串原型上不存在map方法,因此调用时报错 - Prisma返回的
createdAt、updatedAt是Date对象,Next.js在序列化getServerSideProps返回值时不支持直接传递Date类型,因此触发序列化报错
解决方案1(更推荐)
手动转换日期字段为字符串,保留数组结构,无需额外序列化/反序列化操作:
修改Index.tsx中getServerSideProps代码:
export async function getServerSideProps() { console.log("lol"); const comments = await prisma.casinoComment.findMany(); // 遍历转换Date类型字段为ISO字符串 const comments2 = comments.map(item => ({ ...item, createdAt: item.createdAt.toISOString(), updatedAt: item.updatedAt.toISOString() })) console.log(comments2); return { props: { comments2 } }; }
该方案不需要修改子组件核心逻辑,this.props.comments2天然是可遍历的数组类型,也不会触发序列化报错。
解决方案2(保留全量序列化写法)
如果一定要用JSON.stringify处理的话,在前端拿到字符串后先反序列化为数组即可:
修改Home组件逻辑,先解析再传递给子组件:
export default function Home({ comments2 }) { // 先把JSON字符串解析为数组 const parsedComments = JSON.parse(comments2) // 渲染子组件时传入解析后的数组 return <FeaturedCasinos comments2={parsedComments} /> }
额外需要修正的代码问题
- 子组件
render方法返回值写法错误,你当前用了return {},需要改为return (),同时map遍历需要返回DOM元素并补充key属性:
render() { return ( <> {this.props.comments2.map((comment, index) => { return <div key={index}>{comment.content}</div> })} </> ) }
IProps中comments2的类型定义错误,你当前写的是长度为1的元组,需要改为数组类型:
interface IProps { comments2: Array<{ id: number; content: string; createdAt: string; // 按需补充其他字段的类型定义 }>; }
内容的提问来源于stack exchange,提问作者Cult of Tranquility
相关产品推荐
相关产品推荐

