在Nextjs中使用getServerSideProps实现动态路由 [英] Dynamic routing with getServerSideProps in Nextjs

查看:38
本文介绍了在Nextjs中使用getServerSideProps实现动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习下一步。正在使用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;

  <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;

URL动态路由OK。例如,当您点击阿富汗时,URL显示http://localhost:3000/p/Afghanistan

但是,我的国家/地区组件没有显示任何内容,undefined已打印到终端。

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

{
name: "Afghanistan"
}

如果这是个低级问题,我很抱歉。正在尝试学习nextjs

推荐答案

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 } };
}

您将从上面的函数返回嵌套对象

    { props: { country:country } }

所以这个道具将按如下方式附在道具上:

      `props.props`

这就是您应该如何实施

const Country = props => (
  <Layout>
    <h1>{props.props.country.name}</h1>
    <span>{props.props.country.capital}</span>
  </Layout>
);

更新

在我认为在版本9之后更新的next.js的早期版本中,我们没有使用props从服务器端函数返回。截至目前,正确的实施方式是

return {
    props: {
      countries,
    },
  };

这篇关于在Nextjs中使用getServerSideProps实现动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆