繁体   English   中英

如何使用 Next.js 获取基本的外部数据并将组件导入另一个

[英]How to make a basic external data fetch using Next.js and import component into another

我在 pages/github 中有以下代码,当我转到 localhost:3000/github 时,代码按预期执行。 我得到 JSON 数据。

function GithubAPI(props) {
  // Render posts...
  return (<div>{props.data.name}</div>)
}

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://api.github.com/repos/vercel/next.js')

  const data= await res.json()
  console.log(data)

  return {
    props: {
      data,
    },
  }
}

export default GithubAPI

当我将此组件导入另一个组件时,我遇到了问题。

页数/关于

import GithubAPI from './github'
function About(props) {
    console.log(props)

  return (
    <div>
      <div>About</div>
       <GithubAPI/>  {/* TypeError: Cannot read property 'name' of undefined */}

    </div>
  )
}

export default About

我不知道 Next.js 的开发人员如何期望我们构建我们的代码,以便我们可以进行这些类型的 API 调用,并且仍然导出我们的组件以导入其他组件。 我该怎么做?

您不能在任何非页面组件中运行 getStaticProps/getServerSideProps。 一个必须通过道具代替。

暂无
暂无

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

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