当名称有空格时,我遇到了通过我的 API 中的产品名称访问动态路由的问题。当产品名称只有一个词时,我访问路线没有问题。
utils/api.js
export async function getProduct(name) {
const products = await fetchAPI(`/books?name=${name}`);
return products?.[0];
}
pages/books/[name].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/Catalog.js
<Link href='/books/[name]' as={`/books/${_product.name}`}>
答案 0 :(得分:1)
使用 encodeURI 或 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)}`}>