如何覆盖默认的 Next JS 路由行为以终止路径并忽略子路径,同时通过 useRouter 传递整个 URL?
我想使用 URL 地址栏和 Next.js 来访问页面元素,以复制 React Routers 的一些功能。
示例:
我有一个名为 demo 的 Next.js 页面(位于 pages
文件夹中),我可以使用基本的 Next.js 页面路由通过 nextjs.com/demo
访问该页面。
Demo.js
呈现如下:
<div class="demo">
<div id="link1">
...
</div>
<div id="link2">
...
</div>
</div>
我希望能够通过地址栏直接转到我的 #link
锚点。
例如
nextjs.com/demo/link1
带我到 link1
而不是
nextjs.com/demo#link1
(我知道它工作得很好)
我知道我可以提取 /link
部分并将其转换为 #link
并使用 React 路由器访问它,但问题是 Nextjs.com 给了我一个 404 未找到,因为路由器(正确地)认为它是一页。如何告诉路由器此路由的 URL 结尾是 demo?
在没有反应路由器的情况下如何实现这一点?是否有一些中间件魔法可以让我对一组特定的路由执行此操作?
I want to access page elements using the URL address bar with Next.js to replicate some of React Routers' functionality.
Example:
I have a Next.js page called demo (in pages
folder) that I can access with nextjs.com/demo
using basic Next.js page routing.
Demo.js
renders like this:
<div class="demo">
<div id="link1">
...
</div>
<div id="link2">
...
</div>
</div>
I want to be able to go to straight to my #link
anchors via the address bar.
e.g.
nextjs.com/demo/link1
takes me to link1
not
nextjs.com/demo#link1
(which I know works fine)
I know I could extract the /link
section and convert it to a #link
and use the react router to go to it but problem is Nextjs.com gives me a 404 not found because the router (correctly) thinks it's a page. How can I tell the router that the end of the URL for this routing is demo?
How do i achieve this without react router? Is there some middleware magic will allow me to do this for a specific set of routes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论