开发者问题收集

NextJs 动态文件夹路由

2022-02-03
1793

我试图实现这样一种情况,即有两个独立的导航栏,views-nav 带有链接“results”、“statistics”,schools-nav 带有链接“school-a”、“school-b”、“school-c”... 用户首次登陆时,网址看起来会像这样:

  https://example.com/results/school-a 

场景:

  1. 点击 .views-nav link[statistics] => https://example.com/statistics/school-a
  2. 然后点击 .schools-nav link[school-c] => https://example.com/statistics/school-c
  3. 然后点击 .views-nav link[results] => https://example.com/results/school-c
  4. 然后点击 .schools-nav link[school-b] => https://example.com/results/school-b
  5. 然后点击 .views-nav link[statistics] => https://example.com/statistics/school-b

尝试手动访问 https://example.com/statistics/ https://example.com/results/ 应该会重定向到 404。

预期行为:单击 navbar[views] 链接可在结果和统计数据之间切换,同时保持学校 slug;单击 navbar[schools] 链接可在学校之间切换,同时保持视图 slug。

当前文件夹结构是

       -pages
           |
           -[views]
                 |
                 -[schools].js

./Navbar.jsx

    import { useRouter } from "next/router";

    const Navbar = () => {
    
    const { ??? } = useRouter();

    return (

     <nav>
      <div className="views-nav">
       <Link href=`/results/${???}`>
        results
       </Link>
       <Link href=`/statistics/${???}`>
        results
       </Link>
      </div>

      <div className="schools-nav">
       <Link href=`/${???}/school-a`>
        school-a
       </Link>
       <Link href=`/${???}/school-b`>
        school-b
       </Link>
       <Link href=`/${???}/school-c`>
        school-c
       </Link>
      </div>
     </nav>

    )

现在我猜是用 useRouter 做点什么,但我不确定该怎么做🤔🤔。 有人能给我指出正确的方向吗?

1个回答

这应该对你有用。

./Navbar.jsx

import { useRouter } from "next/router";

const Navbar = () => {

const router = useRouter();

return (

 <nav>
  <div className="views-nav">
   <Link href=`/results/${router.query.schools}`>
    results
   </Link>
   <Link href=`/statistics/${router.query.schools}`>
    results
   </Link>
  </div>

  <div className="schools-nav">
   <Link href=`/${router.query.views}/school-a`>
    school-a
   </Link>
   <Link href=`/${router.query.views}/school-b`>
    school-b
   </Link>
   <Link href=`/${router.query.views}/school-c`>
    school-c
   </Link>
  </div>
 </nav>

)
Ankit Gupta
2022-02-03