如何在动态路由中指定可选参数?

编程入门 行业动态 更新时间:2024-10-16 02:29:49
本文介绍了如何在动态路由中指定可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个 page,它将显示本书中每一章的详细信息.用户可以从该页面导航到其他章节,因为屏幕侧边栏中有章节按钮,主要内容显示了章节的详细信息.

Suppose I have a page that will show the details of each chapter in the book. User can navigate to other chapters from that page, as the screen has buttons of chapters in the sidebar, and the main content shows the details of the chapter.

现在用户将从图书列表导航到该页面.在页面信息中,没有那本书的章节信息.

Now the user will navigate to that page from a list of books. At the page information, there's no chapter information of that book.

现在如果URL是\bookSlug,那么页面会显示第一章的详细信息,即使URL中没有提到,它也会获取章节列表然后获取详细信息该列表中的第一章.对于 URL \bookSlug\firstChapterSlug,此行为保持不变.

Now if the URL is \bookSlug, so the page will show the details of the first chapter, even it is not mentioned in the URL, it will fetch the list of chapters then fetch the details of the first chapter from that list. This behaviour remains the same for URL \bookSlug\firstChapterSlug.

所以,在 react-router 中,我曾经这样做过.

So, in react-router I used to do it like this.

<Route path={'/:bookId/:chapterId?'} component={ChapterDetails} >

在页面上,我处理参数,该 ID chapterId 未定义为仅获取第一章或仅获取chapterId 参数中提到的章节.

And on the page, I handle the params, that id the chapterId is undefined to just fetch the first chapter or just fetch the chapter mentioned in the chapterId param.

现在,我被困在这里,

<Link href={'/[bookSlug]/[chapterSlug]' as={'/someBookName'} >

它只是不起作用,即使我已经在 getStaticPaths 可选 GetStaticPaths<Props, {bookSlug: string,chapterSlug?: string}> s 中标记了参数我可以写逻辑.

It is just not working, even I have marked the params in the getStaticPaths optional GetStaticPaths<Props, {bookSlug: string, chapterSlug?: string}> s that I can write logic.

如何在 nextJS 动态路由中实现 react-router 行为?

How can I achieve that react-router behaviour here in nextJS dynamic routing?

推荐答案

从 Next 9.5 开始,您可以使用 可选的所有路由.

Since Next 9.5 you can do it by using optional catch-all routes.

你会有这样的路线/[bookId]/[[...chapterId]].

为了导航,从 Next 9.5.3 你不需要as";Link 中的属性,因此下一步应该正确处理:<Link href='/some-book'/>

And to navigate, since Next 9.5.3 you don't need "as" property in Link so Next sould handle this correctly : <Link href='/some-book'/>

更多推荐

如何在动态路由中指定可选参数?

本文发布于:2023-05-23 15:06:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326443.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   路由   参数   动态   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!