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组件中的props没有

{
  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