简体   繁体   English

Next.js getStaticProps 将数据作为对象传递

[英]Next.js getStaticProps passing data as object

I am new to working with typescript and next.js.我是使用 typescript 和 next.js 的新手。 I am using Vercel to deploy a Next.js webapp that will pull data from a heroku postgresSQL db using Prisma.我正在使用 Vercel 部署 Next.js webapp,它将使用 Prisma 从 heroku postgresSQL 数据库中提取数据。 I am trying to render some data on the page using observable/d3, using getStaticProps to fetch the data, then pass it to the Home page component.我正在尝试使用 observable/d3 在页面上呈现一些数据,使用 getStaticProps 获取数据,然后将其传递给主页组件。

export const getStaticProps: GetStaticProps = async () => {
    let data: Array<object> = await prisma.test.findMany()
    console.log(data)
    return { props: { data } }
}

const Home: NextPage = ( data ) => {
    console.log(data)
    useEffect(() => {
    document.body.append(
        Plot.barY(data, {x: "letter", y: "frequency"}).plot()
    )
 }, [])
 ...
}

The first console log in getStaticProps returns the data in my desired format, an array of objects: getStaticProps 中的第一个控制台日志以我想要的格式返回数据,一个对象数组:

[
 {letter: 'A', frequency: 0.0123}
 ...
 {letter: 'Z', frequency: 0.00234}
]

After passing the data to the Home component, data is wrapped in an object and looks like this:将数据传递给 Home 组件后, data被包裹在一个对象中,如下所示:

 {
  data: [
   {letter: 'A', frequency: 0.0123}
   ...
   {letter: 'Z', frequency: 0.00234}
  ]
 }

My plotting function wants an array of objects, but after passing data using getStaticProps to the Home component, data gets 'wrapped' in those JS Curley braces and I don't want that.我的绘图函数需要一个对象数组,但是在使用 getStaticProps 将data传递给 Home 组件之后, data被“包裹”在那些 JS Curley 大括号中,我不想要这样。 Can someone help me understand why and how to correct this behavior?有人可以帮助我理解为什么以及如何纠正这种行为吗? Using typeof data in both console.log returns object在 console.log 中使用 typeof 数据返回object

You should have been destructured the props Home({ data }) instead of Home(data)你应该已经解构了道具Home({ data })而不是Home(data)

import { InferGetStaticPropsType } from 'next'

type Test = {
  letter: string
  frequency: number
}

export const getStaticProps = async () => {
  let data: Test[] = await prisma.test.findMany()
  return {
    props: {
      data
    }
  }
}

// Destructure the props
const Home: NextPage = ({ data }: InferGetStaticPropsType<typeof getStaticProps>) => {
  // will resolve tests to type Test[]
}

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

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