NextJS:如何从 url 导航到自定义路径?

NextJS: How to navigate from url to a custom path?

我有一个菜单组件用于在我的网站内部导航,例如:

<Link href="/containers/grades/List" as="/grades">

我用 "as" 来保持我的 URL 清洁 但问题是无法刷新导航页面;如果我刷新页面,我会收到 404 错误。

我知道 "as" 用于在 URL 中显示自定义地址,但我需要一种从 URL 访问组件的方法 在这种情况下,我想从 "/grades" 导航到 "/containers/grades/List"

有什么建议吗?

对于动态页面,您可以使用 useRouter 在页面之间进行动态路由。

import React from 'react'
import { useRouter } from 'next/router'

const Dynamic = () => {
  const router = useRouter();
  const { dynamic } = router.query;

  return (
    <div>
      My dynamic page slug: {dynamic}
    </div>
  )
}

导出默认动态 你可以 link 像这样:

<Link href="/[dynamic]" as="/dynamic-page-slug">
  <a>Link to my Dynamic Page</a>
</Link>

您还可以通过添加 next.config.js 文件来创建自定义路线:

// next.config.js
module.exports = {
  async redirects() {
    return [
      // 307 temporary redirect
      {
        source: "/",
        destination: "/under-construction",
        permanent: false,
      },
      // 308 permanent redirect
      {
        source: "/posts",
        destination: "/blog",
        permanent: true // permanent redirect
      },
      // With parameter and custom status code
      {
        source: "/photos/:id",
        destination: "/photo/:id",
        statusCode: 303 // see other
      }
    ];
  }
};

使用 <Link href="/containers/grades/List" as="/grades"> 你有客户端路由,对于服务器端,只需将下面的代码添加到你的 next.config.js;

 experimental: {
      async rewrites() {
        return [
          { source: '/grades', destination: '/containers/grades/List' }
          ];
       }
    }

这将把它们连接起来。