如何在动态路由中指定可选参数? [英] How can I specify the optional parameters in the dynamic routing?

查看:51
本文介绍了如何在动态路由中指定可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 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'/>

这篇关于如何在动态路由中指定可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆