简体   繁体   English

如何在 Next.js 中为同一页面使用不同的路由?

[英]How to use different routes for a same page in Next.js?

Next.js manages routing from the /pages folder, but I would like to use two different routes for a same component. Next.js 从/pages文件夹管理路由,但我想为同一个组件使用两个不同的路由。

I want to have an /about route and a /a-propos route that both render the component in the about.js file.我想要一个/about路由和一个/a-propos路由,它们都在about.js文件中呈现组件。

mywebpage.com/about         To show -> pages/about/index.js

and

mywebpage.com/a-propos      To show -> pages/about/index.js

Is there an official way of achieving that?有没有官方的方法来实现这一点?

I'd refactor your page component into a more general component directory, add a folder called a-propos to your /pages directory and then reference the general component from both /pages/about/ and /pages/a-propos .我会将您的页面组件重构为一个更通用的组件目录,将一个名为a-propos的文件夹添加到您的/pages目录,然后从/pages/about//pages/a-propos引用通用组件。

If you want to intercept routing requests and do something more exotic, take a look at the docs for useRouter如果您想拦截路由请求并做一些更奇特的事情,请查看useRouter的文档

The official way to do this is with rewrites:这样做的官方方法是重写:

NextJS Rewrites NextJS 重写

module.exports = {
  async rewrites() {
    return [
      {
        source: '/a-propos',
        destination: '/about',
      },
    ]
  },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM