简体   繁体   English

在next.js中进行路由的最佳方法是什么

[英]What is the best way to do a route in next.js

I'm a bit of a beginner at javascript but I am using next routes which uses path-to-regexp under the hood. 我对javascript有点初学者,但是我正在使用下一条路线,该路线在幕后使用path-to-regexp。

I have a page that has a list of links. 我有一个页面,其中包含链接列表。 The route for this page is /locations/s-:specialty-providers with "specialty" being the only dynamic part. 该页面的路由是/locations/s-:specialty-providers其中“ specialty”是唯一的动态部分。

When I click on one of the links on the page, it reroutes me to /locations/ss-:specialty-providers/:abbr (where both specialty and abbr are dynamic) when it should be rerouting to /locations/s-:specialty-providers/:abbr . 当我单击页面上的链接之一时,当我应将其重新路由到/locations/s-:specialty-providers/:abbr时,它会将我重新路由到/locations/ss-:specialty-providers/:abbr (其中special和abbr都是动态的) /locations/s-:specialty-providers/:abbr

Routes file: 路线文件:

{ name: 'sitemap-providers-location-procedure', page: 'sitemap/providers/by_location/by_procedure', pattern: '/locations/:procedure-providers' }, { name: 'sitemap-specialties-location-city', page: 'sitemap/specialties/by_location/by_city', pattern: '/locations/s-:specialty-providers/:abbr' },

Next.js will give you routing out of the box with putting your file in pages directory Next.js将文件放在pages目录中,可让您开箱即用

Let's say you have pages/index.js 假设您有pages/index.js

    import Link from 'next/link'

function getSitemaps () {
  return [
    {
      id:"1",
      title: "sitemap-providers-location-procedure",
      s: "providers",
      abbr: "by_procedure",
    },
    {
      id:"2",
      title: "sitemap-specialties-location-city",
      s: "specialties",
      abbr: "by_city",
    }
  ]
}

const SitemapLink = ({post}) => (
  <li>
    <Link as={`/sitemap/${post.s}/by_location/${post.abbr}`} href={`/sitemap?title=${post.title}`}>
      <a>{post.title}</a>
    </Link>
  </li>
)

export default () => (
<div>
  <h1>Links</h1>
  <ul>
    {getSitemaps().map((sitemap) => (
      <SitemapLink key={sitemap.id} post={sitemap}/>
    ))}
  </ul>
</div>
)

and there is another file pages/sitemap.js 还有另一个文件pages/sitemap.js

    import {withRouter} from 'next/router'

const Page = withRouter((props) => (
  <div>
    <h1>{props.router.query.title}</h1>
    <p>This is the page content.</p>
  </div>
))

export default Page

Now you have that dynamic routes. 现在,您有了动态路线。

You don't need any magic or pattern in next.js to create route. 在next.js中,您不需要任何魔术或图案即可创建路由。

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

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