在 Nextjs 中使用 getServerSideProps 进行动态路由

DGB*_*DGB 11 reactjs next.js

我正在尝试学习nextjs。正在努力使用getServerSideProps.

使用免费的 api,我在 DOM 上显示了一个国家列表。我想动态链接到一个国家/地区,并为该特定国家/地区获取和显示数据。

到目前为止,这是我的代码

const Country = props => (
  <Layout>
    <h1>{props.country.name}</h1>
    <span>{props.country.capital}</span>
  </Layout>
);
export async function getServerSideProps(context) {
  const { id } = context.query;
  const res = await fetch(`https://restcountries.eu/rest/v2/name/${id}`);
  const country = await res.json();

  console.log(`Fetched place: ${country.name}`);
  return { props: { country } };
}
export default Country;

Run Code Online (Sandbox Code Playgroud)
  <div className='container'>
    <Head>
      <title>Countries List</title>
      <link rel='icon' href='/favicon.ico' />
    </Head>
    <Layout>
      <main>
        <h1>
          Countries{' '}
          <span role='img' aria-label='world emoji'>
            
          </span>
        </h1>
        <ul>
          {countries.map(country => (
            <li key={country.name}>
              <Link href='/p/[id]' as={`/p/${country.name}`}>
                <a>{country.name}</a>
              </Link>
            </li>
          ))}
        </ul>
      </main>
    </Layout>
  </div>
);

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const res = await fetch('https://restcountries.eu/rest/v2/all');
  const countries = await res.json();

  // By returning { props: posts }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      countries,
    },
  };
}

export default Home;

Run Code Online (Sandbox Code Playgroud)

URL 动态路由确定。例如,当您单击阿富汗时,网址会显示http://localhost:3000/p/Afghanistan

然而,我的国家/地区组件不显示任何内容并undefined打印到终端。

来自 URL 的 url 和响应示例: https://restcountries.eu/rest/v2/name/Afghanistan

{
name: "Afghanistan"
}
Run Code Online (Sandbox Code Playgroud)

抱歉,如果是菜鸟问题。尝试学习nextjs

Yil*_*maz 11

export async function getServerSideProps(context) {
  const { id } = context.query;
  const res = await fetch(`https://restcountries.eu/rest/v2/name/${id}`);
  const country = await res.json();

  console.log(`Fetched place: ${country.name}`);
  return { props: { country } };
}
Run Code Online (Sandbox Code Playgroud)

你正在从上面的函数返回一个嵌套对象

    { props: { country:country } }
Run Code Online (Sandbox Code Playgroud)

所以这个道具将像这样附加到道具上:

      `props.props`
Run Code Online (Sandbox Code Playgroud)

这是你应该如何实施

const Country = props => (
  <Layout>
    <h1>{props.props.country.name}</h1>
    <span>{props.props.country.capital}</span>
  </Layout>
);
Run Code Online (Sandbox Code Playgroud)

  • 如果它对任何人有帮助,这个答案是完全错误的 - 尽管它可能已经过时了。在 2020 年,接下来的 getServerSideProps 要求您返回一个包含关键字 props 的对象,以便您的 props 进入与其一起导出的组件中。 (3认同)