简体   繁体   English

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

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

I am trying to iterate through an array of food objects and create static pages for each one based on its title.我正在尝试遍历一系列食物对象并根据其标题为每个对象创建静态页面。 This works for most of the foods, but if the food title contains a / , then navigating to the page (such as the "Nice strawberry/kiwis dessert" page ) will throw a 404.这适用于大多数食物,但如果食物标题包含/ ,则导航到该页面(例如“Nice strawberry/kiwis dessert”页面)将抛出 404。

In the home page, I encode the URL when I create the Link and then in the getStaticPaths function , I create the paths using the same encoded link.在主页中,我在创建Link时对 URL 进行编码,然后在getStaticPaths函数中,我使用相同的编码链接创建paths However, it doesn't seem to work when deployed.但是,它在部署时似乎不起作用。

The page does work locally when running npm run dev , but it seems that in the actual output build there are issues.该页面在运行npm run dev时在本地工作,但似乎在实际输出构建中存在问题。 Is there something I can do to allow paths with encoded slashes to work?我可以做些什么来允许带有编码斜杠的路径工作吗?


Home page主页

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>
  </>
)

Food page食物页面

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

The example I posted here is a bit contrived, for my actual app I was able to get it to work by using fallback: 'blocking' .我在这里发布的示例有点做作,对于我的实际应用程序,我能够通过使用fallback: 'blocking'来让它工作。 It's not a totally exportable static website anymore unfortunately, but I only have a few pages that will run into this issue so it's fine that a few of them will have a slight loading time from the server.不幸的是,它不再是一个完全可导出的静态网站,但我只有几个页面会遇到这个问题,所以其中一些页面从服务器加载时间稍长一点也没有关系。


https://nextjs.org/docs/basic-features/data-fetching 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. // { fallback: blocking } 将服务器渲染页面 // 如果路径不存在则按需。 return { paths, fallback: 'blocking' }返回{路径,后备:'阻塞'}

Ofc, because you have / in the path. Ofc,因为你有/在路径中。 %2F symbol representing / %2F符号代表/

Just make custom function for path encoding and use it只需为path编码制作自定义函数并使用它

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

Use nextjs Router.使用 nextjs 路由器。

Use can add onclick function for link tag使用可以为链接标签添加onclick功能

Refer nextjs Router https://nextjs.org/docs/api-reference/next/router参考 nextjs 路由器https://nextjs.org/docs/api-reference/next/router

An old thread, but I've spent many hours looking for a solution so I'd like to share.一个旧线程,但我花了很多时间寻找解决方案,所以我想分享一下。

In order to get links in the format /categories/page in getStaticPath, and at the same time to use the same component in the /category/ and in the /category/page/, but with different parameters, you should use the page format [...category].js.为了在 getStaticPath 中获取格式为 /categories/page 的链接,同时在 /category/ 和 /category/page/ 中使用相同的组件,但参数不同,您应该使用页面格式[...类别].js。 This allows you to pass parameters in getStaticPaths as an array:这允许您将 getStaticPaths 中的参数作为数组传递:

params: {
    category: [category, page],
}

In result it will generate page category/page and still have fallback: false.结果它将生成页面类别/页面并且仍然有回退:false。 Trying to add '/' directly to the path (as you did) creates html pages category%2fpage.html.尝试将“/”直接添加到路径(就像您所做的那样)会创建 html 页面类别 %2fpage.html。

More details about static pathsAnd about catch all routes 有关静态路径和捕获所有路由的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM