简体   繁体   中英

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.

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.

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 .

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

Let's say you have 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

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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