【问题标题】:Adding symbol (e.g. @) in front of slug in NextJS route在 NextJS 路由中的 slug 前面添加符号(例如 @)
【发布时间】:2021-05-29 00:36:39
【问题描述】:

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

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

这可能吗?

【问题讨论】:

  • 您只需在地址栏中输入,@username 将作为参数传递给您的动态路由[username].js

标签: javascript node.js reactjs routes next.js


【解决方案1】:

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

Working example on 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>
}

【讨论】:

    【解决方案2】:

    尝试使用rewrites 和一些正则表达式。 Next.js 在后台使用path-to-regexp

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

    在客户端使用next/link:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 2022-01-05
      • 2021-12-04
      • 2023-04-09
      • 2013-08-23
      • 2021-05-04
      • 2018-02-01
      相关资源
      最近更新 更多