【问题标题】:nextjs dynamic routing problem with spacesnextjs 带空格的动态路由问题
【发布时间】:2021-04-30 05:21:55
【问题描述】:

当名称包含空格时,我遇到了通过我的 API 中的产品名称访问动态路由的问题。当产品名称只有一个单词时,我访问路由没有问题。

utils/api.js

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

页面/书籍/[名称].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}`}>

【问题讨论】:

    标签: javascript reactjs url next.js pathname


    【解决方案1】:

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

    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)}`}>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-08
      • 2020-09-08
      • 2021-08-12
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多