【问题标题】:TypeScript+NextJS destructuringTypeScript+NextJS 解构
【发布时间】:2021-12-23 09:41:51
【问题描述】:

我有来自 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组件的?
  • "Home" 是 pages/index.tsx 中的主要组件
  • 我可以得到这个对象 if = (userNote: any) => { ... } 但这是错误的

标签: typescript next.js prisma


【解决方案1】:

问题是你在 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

【讨论】:

  • 谢谢,现在可以使用了!
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2022-12-01
  • 2021-09-18
  • 1970-01-01
  • 2020-10-09
  • 2021-04-10
  • 2020-10-22
相关资源
最近更新 更多