带空格的nextjs动态路由问题

nextjs dynamic routing problem with spaces

我在 API 中通过产品名称访问动态路由时遇到问题,但名称中有空格。我在产品名只有一个字的情况下访问路由没问题

utils/api.js

export async function getProduct(name) {
  const products = await fetchAPI(`/books?name=${name}`);
  return products?.[0];
}

pages/books/[名字].js

// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get products
  const products = await getProducts();
  // Get the paths we want to pre-render based on posts
  const paths = products.map((product) => `/books/${product.name}`)
  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

/components/Catalogue.js

<Link href='/books/[name]' as={`/books/${_product.name}`}>

使用encodeURI or encodeURIComponent。这对特殊字符(如空格)进行编码,以确保它们不会被浏览器/服务器误解。 您的代码应如下所示:

export async function getStaticPaths() {
  const products = await getProducts();
  const paths = products.map((product) => `/books/${encodeURIComponent(product.name)}`)
  return { paths, fallback: false }
}

<Link href='/books/[name]' as={`/books/${encodeURIComponent(_product.name)}`}>