是否可以在静态构建上下文中将动态路由路径与nextJS一起使用?
假设我的构建是一组可以在任何Web服务器(Apache,Nginx,S3,Netlify等)上托管的html,js,css资产。
例如,我有一个定义的路径/pages/[article].js/read
,我希望能够使用以下结构:/page/articleA/read
,其中articleA
是动态变量。
如果可行,如何实现?
答案 0 :(得分:1)
是的,当与nextjs一起使用静态站点生成时,可以使用动态路由。您必须使用数据获取方法getStaticProps
来基于动态路由参数获取所需的数据。另外,您还必须使用另一个函数getStaticPaths
来生成paths
的列表,nextjs将在构建时为其构建静态页面。例如,
假设第/pages/articles/[articleId].js
页,这是您的伪代码。
// you have to generate and return a list of paths
export const getStaticPaths = async () => {
const articles = await /*Fetch the articles from backend or make a db query*/
const paths = articles.map(article => ({ params: { articleId: article.id }}));
return {
paths,
fallback: false
}
}
export const getStaticProps = async (ctx) => {
const articleId = ctx.params.articleId;
// fetch the data using the article id and return as props
return {
props: /* fetched data */
}
}
// create the page component and export it as the default export
您可以在docs中了解更多信息。请记住,因为fallback
设置为false
nextjs将显示404
页面,显示未从函数getStaticPaths
返回的任何路径,您可以阅读{{ 1}} here。