我将使用路由器从一个页面转到另一个页面:
const goToArticle = (index) => {
router.push({
pathname: `/article/${index}`,
})
}
我要访问的页面命名为[id].js
,并导出为Article
在文章页面中,我试图获得索引:
export async function getStaticPaths({id}) {
const res = await fetch('myurl');
const articles = await res.json();
console.log(params.id);
return {
props: {
article: articles.items[id]
}
}
}
错误:ID未定义
TypeError:无法按原样销毁"undefined"的属性"id"未定义。
如何获取该索引并返回具有该索引的数组项?
您可以如下更改函数重定向:
const goToArticle = (index) => {
router.push({
pathname: `/article/[id]`,
as: `/article/${index}`,
})
}
请参阅文件:https://nextjs.org/docs/api-reference/next/router