Nextjs 中使用 getServerSideProps 进行动态路由

Dynamic routing with getServerSideProps in Nextjs

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

计算路由

使用免费 API 我在 DOM 上显示了一个国家列表。我想动态地 link 到一个国家并为该特定国家获取和显示数据。

这是我目前的代码

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 动态路由正常。例如,当您单击阿富汗时,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>
);

更新

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

return {
    props: {
      countries,
    },
  };

只是为了添加到已接受的答案中,您还可以解构以使其(恕我直言)更具可读性。这完全是可选的

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

您处理页面动态路由的方式没有任何问题。问题是 API 返回的数据是 array 但您的代码期望它是 object。您可以从数组中检索第一项并将其传递给来自 getServerSideProps.

的组件
export async function getServerSideProps(context) {
    const { id } = context.params; // Use `context.params` to get dynamic params
    const res = await fetch(`https://restcountries.com/v2/name/${id}`); // Using `restcountries.com` as `restcountries.eu` is no longer accessible
    const countryList = await res.json();
    const [country] = countryList; // Get first item in array returned from API

    return { props: { country } };
}

const Country = ({ country }) => {
    console.log(country);
    
    return (
        <>
            <h1>{country.name}</h1>
            <span>{country.capital}</span>
        </>
    );
};

export default Country;