简体   繁体   English

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

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

I have the code below in pages/github and when I go to localhost:3000/github the code executes as expected.我在 pages/github 中有以下代码,当我转到 localhost:3000/github 时,代码按预期执行。 I get JSON data.我得到 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

When I import this component into another component I get problems.当我将此组件导入另一个组件时,我遇到了问题。

pages/about页数/关于

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

I do not know how the developers of Next.js expect us to structure our code so that we can make these kinds of API calls and still export our components for import into other components.我不知道 Next.js 的开发人员如何期望我们构建我们的代码,以便我们可以进行这些类型的 API 调用,并且仍然导出我们的组件以导入其他组件。 How am I expected to do this?我该怎么做?

You cannot run getStaticProps/getServerSideProps in any non-page components.您不能在任何非页面组件中运行 getStaticProps/getServerSideProps。 One must prop pass instead.一个必须通过道具代替。

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

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