繁体   English   中英

TypeScript+NextJS 解构

[英]TypeScript+NextJS destructuring

我有来自 postgresql 的对象:

在此处输入图片说明

需要像这样在 NextJS 组件上获取 id、名称和内容:

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: {
      userNote: data,
    },
  }
}
interface INote {
  id: number
  name: string
  content: string
}

const Home = ({ name, content, id }: INote) => {
  console.log(name)
  return <div>hello world</div>
}

但我没有定义。 怎么了?

问题是你在 Home 组件中的道具不是

{
  id: number
  name: string
  content: string
}

但实际上,

{
 userNote: {
  id: number
  name: string
  content: string
 }
}

您要么需要更改解构和类型:

const Home = ({ userNote: { name, content, id } }: { userNote: INote }) => {

或者你可以改变你的 getServerSideProps:

export async function getServerSideProps() {
  const data = await prisma.note.findFirst()
  return {
    props: data,
  }
}

根据我的经验,采用第一种方法并将其更改为:

export async function getServerSideProps() {
  const data = { id: 1, name: 'test', content: 'content' }
  return {
    props: {
      userNote: data,
    },
  }
}

interface INote {
  id: number
  name: string
  content: string
}

interface HomeProps {
   userNote: INote
}

const Home = ({ userNote: { name, content, id } }: HomeProps) => {
  console.log(name)
  return <div>hello world</div>
}

export default Home

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM