NextJS URL params like React-Router

前端 未结 5 1207
一整个雨季
一整个雨季 2021-02-19 06:56

I\'m a newbie to NextJS, It looks so good on the first impression. But after giving it a chance I\'ve faced some problems like URL routing with custom params like react-router.<

相关标签:
5条回答
  • 2021-02-19 07:28

    this example will help you define your parameterized, named routes. it uses nest/routes and let you define your custom routes of preference. hope it will help you.

    https://github.com/zeit/next.js/tree/master/examples/with-next-routes

    0 讨论(0)
  • 2021-02-19 07:33

    I have been through the same issue, but I found this package, https://github.com/fridays/next-routes

    It works almost the same as react-router, I have tried it and it works for me.

    0 讨论(0)
  • 2021-02-19 07:42

    First import Router

    import Router from 'next/router'
    

    Then if you want to use it in a Link tag

    <Link href={{ pathname: '/about', query: { name: 'Sajad' } }}>
    

    If you want to use it in a function or after a callback

    Router.push({
        pathname: '/about',
        query: { name: 'Sajad' },
      })
    
    0 讨论(0)
  • 2021-02-19 07:49

    For older version: < 9.x

    You can use next/link's as feature:

    <Link prefetch as={`/product/${slug}`} href={`/product?slug=${slug}`}>
    

    Link on the browser will appear as /product/slug which internally maps to /product?slug=slug

    You need to have a custom server for server-side mapping:

    server.get("/product/:slug", (req, res) => {
      return app.render(req, res, "/product", { slug: req.params.slug })
    })
    

    For 9.x and higher

    Next 9.x supports file system based dynamic routing. You don't need a custom server anymore.

    Next.js supports creating routes with basic named parameters, a pattern popularized by path-to-regexp (the library that powers Express).

    Creating a page that matches the route /product/:slug can now be achieved by creating a file in your pages directory named: pages/product/[slug].js.

    Multiple dynamic URL segments are also supported!

    ./pages/blog/[blogId]/comments/[commentId].js
    ./pages/posts/[pid]/index.js
    
    0 讨论(0)
  • 2021-02-19 07:52

    For anyone arriving late to this party, we now have dynamic routing in Next 9.

    Which would allow for a url structure to be crafted like this by using the file structure, and without additional packages.

    You could create a file pages/user/[id].js

    With

    import { useRouter } from 'next/router'
    
    const User = () => {
      const router = useRouter()
      const { id } = router.query
    
      return <p>User: {id}</p>
    }
    
    export default User
    
    0 讨论(0)
提交回复
热议问题