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

问题描述 投票:0回答:2

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

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

我使用“ as”保持网址清洁但是问题是导航页面无法刷新;如果刷新页面,则会显示404错误。

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

有什么建议吗?

reactjs next.js
2个回答
0
投票

对于动态页面,您确实可以使用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 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
      }
    ];
  }
};

0
投票

使用<Link href="/containers/grades/List" as="/grades">,您有客户端路由,对于服务器端,只需将以下代码添加到next.config.js中即可。

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

这将把它们连接起来。

© www.soinside.com 2019 - 2024. All rights reserved.