Nextjs中的getServerSideProps动态路由

时间:2020-04-15 06:38:28

标签: 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;

  <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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

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