簡體   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