NextJS URL params like React-Router

前端 未结 5 1245
一整个雨季
一整个雨季 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:49

    For older version: < 9.x

    You can use next/link's as feature:

    
    

    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
    

提交回复
热议问题