【发布时间】:2020-07-28 01:38:30
【问题描述】:
我正在努力学习 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
【问题讨论】:
标签: javascript reactjs next.js server-side-rendering