在 NextJS 路由中的 slug 前面添加符号(例如@)

IT技术 javascript node.js reactjs routes next.js
2021-05-08 20:09:54

我正在尝试@在 slug URL 前面添加例如:https://example.com/@username

我试过了,@[username].js但这不起作用。

这甚至可能吗?

2个回答

尝试使用重写和一些正则表达式。Next.js 在幕后使用路径到正则表达式

  async rewrites() {
    return [
      {
        source: '/:userId(@[a-zA-Z0-9]+)/:id*',
        destination: "/user/:userId/:id*",
      }
    ]
  }

在客户端使用next/link

<Link href={`@${userId}`}>
  <a>user</a>
</Link>

在您处理用户的后端,将 放入@用户的用户名中。然后,只需将用户名视为纯文本 slug。这是有效的,因为@在 URL 中是允许的,就像a,bc

StackBlitz 上的工作示例

pages/index.js

import Link from 'next/link'

const username = '@foobar' // hardcoded example username, this will be recieved from your backend

export default function Index() {
    return (
        <Link href={username}>
            <a>{username}</a>
        </Link>
    )
}

pages/[username].js

import { useRouter } from 'next/router'

export default function Username() {
    const router = useRouter()
    const { username } = router.query

    return <h1>User: {username}</h1>
}