Next.js – encodeURIComponent 不适用于 `getStaticPaths` 中的 `/`

Next.js – encodeURIComponent doesn't work with `/` in `getStaticPaths`

我正在尝试遍历一组食物 objects 并根据每个食物的标题为其创建静态页面。这适用于大多数食物,但如果食物标题包含 /,则导航到页面(例如 the "Nice strawberry/kiwis dessert" page)将抛出 404。

在主页中,我在 create the Link and then in the getStaticPaths function 时对 URL 进行编码,我使用相同的编码 link 创建 paths。但是,部署时似乎不起作用。

当 运行 npm run dev 时,该页面在本地工作,但似乎在实际输出构建中存在问题。我可以做些什么来让带有编码斜杠的路径起作用吗?


首页

const HomePage: NextPage = () => (
  <>
    <h1>Home</h1>
    <ul>
      {foods.map((food) => (
        <li key={food.title}>
          <Link href={`/food/${encodeURIComponent(food.title)}`}>
            {food.title}
          </Link>
        </li>
      ))}
    </ul>
  </>
)

美食页

export const getStaticProps: GetStaticProps<Props, Params> = (ctx) => {
  const title = ctx.params?.foodTitle as string
  const food = foods.find((food) => food.title === title) as Food

  return {
    props: {
      food
    }
  }
}

export const getStaticPaths: GetStaticPaths = () => {
  const paths = foods.map((food) => `/food/${encodeURIComponent(food.title)}`)

  return {
    paths,
    fallback: false
  }
}

const FoodPage: NextPage<Props> = ({ food }) => {
  return (
    <>
      <Link href='/'>Go Back</Link>
      <h1>{food.title}</h1>
      <h2>Amount: {food.amount}</h2>
    </>
  )
}

export default FoodPage

Ofc,因为路径中有 /%2F 符号代表 /

只需为 path 编码制作自定义函数并使用它

static stringToParamUrl(input: string) {      
    let url = input.normalize("NFD").toLowerCase().replace(/[\u0300-\u036f]/g, "").replace(/[^a-zA-Z0-9-_]/g, "-")
    return url
  }

修改:我使用相同的编码 link 创建路径。但是,它在部署时似乎不起作用。”如果它起作用了,那是不正确的。除了包含“/”的那些 link,您的其他 link 正在工作。 “/”是 URL 的保留字符。在下一个 js 中,它作为“分隔符”工作。

还有(关于Link): 您 need to have <a>Link

中添加标签
<Link><a>something</a></Link>

另外(关于 回退):

回退 is not changing the URL 逻辑。使用回退将在“第一个需求”上生成静态页面——与 URL 无关。 你在部署期间没有错误,因为你没有创建静态页面(fallback false)

您需要: “我正在尝试遍历一组食物 objects 并根据其标题为每个食物创建静态页面。” = 您需要在数据库中添加一个名为“URL”或类似的东西,并根据 URL *您之前在创建数组时生成的元素)而不是名称来迭代元素,因为:

  1. 您需要具有“唯一”URL(通过 [pid] 参数或其他方式从您的 api 获取数据)
  2. 您需要 avoid reserved and forbidden 个符号 URL
  3. 不如美化一下url。 (我和你分享了一个功能)

可能我没有正确理解你的问题

我在此处发布的示例有点做作,对于我的实际应用程序,我能够通过使用 fallback: 'blocking' 使其正常工作。不幸的是,它不再是一个完全可导出的静态网站,但我只有几个页面会 运行 解决这个问题,所以其中一些页面从服务器加载的时间会很短也没关系。


https://nextjs.org/docs/basic-features/data-fetching

// We'll pre-render only these paths at build time. // { fallback: blocking } will server-render pages // on-demand if the path doesn't exist. return { paths, fallback: 'blocking' }