next.js 无法使用getStaticProps()- Nextjs导出数据

a0zr77ik  于 2022-11-05  发布在  其他
关注(0)|答案(2)|浏览(276)

你好,我正在尝试用react和NextJS实现服务器端渲染。我正在尝试从一个API中提取一些信息,这些信息可以在我的主页上使用,但我遇到了一些问题。例如,如下面我的代码所示,“属性'map'不存在于类型”。我的代码如下:

import type { NextPage } from 'next'
import Head from 'next/head'
import Header from '../components/Header'
import Banner from '../components/Banner'

const Home: NextPage = (exploreData) => {
  return (
    <div className="">
      <Head>
        <title>Don Airbnb</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header/>
      {/*Banner*/}
      <Banner/>

      <main className="max-w-7xl mx-auto px-8 sm:px-16">
        <section className="pt-6">
          <h2 className="text-4xl font-semibold pb-5">Explore Nearby</h2>

          {/* Pull data from a server - API endpoints */}
          {exploreData.map(item => {
            <h1>{item.location}</h1>
          })}
        </section>
      </main>

    </div>
  )
}

export async function getStaticProps() {
  const exploreData = await fetch('https://links.papareact.com/pyp').then(res => res.json());
  return {
    props: {
      exploreData
    }
  }
}

但是,我收到以下错误:

Server Error
Error: page / getStaticProps can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member

我怎样才能解决这个问题?

ddrv8njm

ddrv8njm1#

您的页面组件必须是默认导出,并且在您的页面组件之前导出您的getStaticProps

export async function getStaticProps() {
  const exploreData = await fetch('https://links.papareact.com/pyp').then(res => res.json());
  return {
    props: {
      exploreData
    }
  }
}
const Home: NextPage = (exploreData) => {
  return (
    <div className="">
      <Head>
        <title>Don Airbnb</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header/>
      {/*Banner*/}
      <Banner/>

      <main className="max-w-7xl mx-auto px-8 sm:px-16">
        <section className="pt-6">
          <h2 className="text-4xl font-semibold pb-5">Explore Nearby</h2>

          {/* Pull data from a server - API endpoints */}
          {exploreData.map(item => {
            <h1>{item.location}</h1>
          })}
        </section>
      </main>

    </div>
  )
}
export default Home: NextPage;
nafvub8i

nafvub8i2#

您必须导出组件,也在底部,如下图所示

export default Home:NextPage;

试着像这样使用

export async function getStaticProps() {
  const exploreData = await fetch('https://links.papareact.com/pyp').then(res => res.json());
  return {
    props: {
      exploreData: JSON.parse(JSON.stringify(exploreData))
    }
  }
}

相关问题