【问题标题】:how to add dash(-) between name of dynamic route Nextjs in url如何在 url 中的动态路由 Nextjs 的名称之间添加破折号(-)
【发布时间】:2022-01-05 04:19:41
【问题描述】:

我创建了一个动态路由 pages/post/[postname].tsx 。当我将名称发送到动态路由时,url 会显示带有 url-encode (%20,%E2,...) 的名称 我想在单词之间用破折号显示网址的名称。像下面的网址

https://stackoverflow.com/questions/68041539/using-dash-in-the-dynamic-route-name-in-nuxt-js

我该怎么做?

【问题讨论】:

  • 你能澄清一下“当我将名字发送到动态路由时”的意思吗

标签: next.js nextjs-dynamic-routing


【解决方案1】:

我之前使用过 getStaticPaths 方法并将它传递给一个 slugs 对象。在处理无头 CMS 时,这对我有用。

export async function getStaticPaths() {
  // Hit API to get posts as JSON
  const posts = await getPosts()

  // Map a new object with just the slugs
  const paths = posts.map((post) => {
    return { params: { slug: post.slug } }
  })

// Return paths 
  return {
    paths: paths,
    fallback: true
  }
}

【讨论】:

    【解决方案2】:

    我想我理解这个问题,你正在尝试使用一组带空格的字符串,例如“开始 Web 开发的基础”作为路径参数来实现类似 https://www.geniushawlah.xyz/the-fundamentals-of-starting-web-development 的东西。这很可能会将您的空间转换为%20,这是正常的。我会建议您首先使用replace() 方法将所有空格更改为连字符,然后再将其作为参数传递,但replace() 方法仅更改第一个空格并保留其余空格。还有其他方法可以以编程方式消除空格,但可能会带来压力且不值得,因此我建议您默认使用带连字符的字符串集。

    如果不是,请尝试使用带有 replace() 方法的 for 循环将所有空格更改为连字符,然后将其作为参数传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 2018-05-16
      • 1970-01-01
      • 2014-06-26
      • 2017-09-24
      • 2021-12-04
      • 2023-03-05
      • 2013-02-04
      相关资源
      最近更新 更多