我已经搜索了很多关于这个主题的文章和帖子,但是它们对我来说似乎没有太大的意义。我对Nextjs和动态路由一般都是新手,所以我希望有人能为我的情况解释清楚。
我的页面结构看起来像下面这样。我想做的是把路径合并成一个。所以我会有这样的东西:
-Page
--Category
---[slug].js
--Post
---[slug].js
我理解这种结构是如何工作的,我最终会得到两条不同的路径,一条是域/类别/[slug],另一条是域/帖子/[slug]。
这不是我想要的。我想要的是域/类别/[slug]/帖子/[slug]。
我也尝试过像下面这样嵌套文件夹结构,虽然我不确定这是否可行,或者我只是做得不正确。更不用说很多变化和结构了。我已经厌倦了用头撞墙。
-Page
--Category
---index.js
---[slug].js
---Post
----[slug].js
我很确定答案在于使用像[... params]这样的catch all,我只是不确定正确的方法,这对我来说有意义。
下面是我使用的代码的一个示例:https://github.com/adrianhajdin/project_graphql_blog/tree/main/pages
我的结构完全一样,只是文件夹和名称可能不同。
编辑:我还应该注意,我没有问题,改变目前的网站文件夹结构来完成这一点。我只是不想改变我的CMS结构,我目前已经建立。
1条答案
按热度按时间brccelvz1#
您可以使用下列结构来达成此目的:
请注意,在文件夹
category
中不能使用名称[slug]
两次,因为我们必须返回带有路径名的对象作为键,例如[category] -〉{category:...},[鼻涕虫] -〉{鼻涕虫:...},因此它们必须是唯一的,以便next告诉您要返回getStaticPaths
中的slugs的文件夹。现在,如果使用
getStaticPaths
,则需要返回页面的特定slug,以及params: {...}
中潜在父页面的“slug”,以便预先生成页面。因此在
category/[category]/index.js
中,您需要执行以下操作:然后在
getStaticProps
中可以访问它,如下所示:...
同样的概念也适用于
category/[category]/[slug].js
,只是现在必须返回/处理getStaticPaths
和getStaticProps
中的两个“slugs”[category]
和[slug]
:以及在
getStaticProps
中:例如,现在可以在
localhost:3000/category/category-A/some-post-for-category-A
下访问其中一篇文章