NextJS+Prisma场景下组件解构props得到undefined的原因是什么?
问题原因
你在getServerSideProps中返回的props结构是顶层只有userNote一个属性,查询到的id/name/content三个字段都挂载在userNote对象下,而组件直接从顶层props解构这三个字段,自然会返回undefined。
修复方案
方案1:调整组件的解构逻辑
修改组件参数的解构层级,先取出userNote再解构内部字段,同时调整类型定义:
export async function getServerSideProps() { const data = await prisma.note.findFirst() // 增加空值判断,避免查询不到数据时报错 if (!data) { return { notFound: true } } return { props: { userNote: data, }, } } interface INote { id: number name: string content: string } // 先取userNote,再解构内部字段,同时标注类型 const Home = ({ userNote: { name, content, id } }: { userNote: INote }) => { console.log(name) return <div>hello world</div> }
方案2:调整getServerSideProps的返回结构
如果不想修改组件代码,可以直接把查询到的字段展开到顶层props:
export async function getServerSideProps() { const data = await prisma.note.findFirst() if (!data) { return { notFound: true } } return { props: { ...data, // 直接把id/name/content展开到顶层props }, } } interface INote { id: number name: string content: string } // 原有组件代码不需要修改 const Home = ({ name, content, id }: INote) => { console.log(name) return <div>hello world</div> }
内容的提问来源于stack exchange,提问作者Denis
相关产品推荐
相关产品推荐

