Wil*_*ker 18 javascript routes next.js dynamic-routing
更新:
getServerSideProps?index.js在产品文件夹下执行此操作,它有效,这意味着它可以与 [category_slug] 配合使用getServerSideprops,对吗?这是我的文件夹结构
pages
   |-categories
       |-[category_slug]
           |-index.js     
           |-product
               |-[product_slug].js       
Run Code Online (Sandbox Code Playgroud)
当我输入时,它会导致错误[product_slug]。显示:
错误:未在 /categories/[category_slug]/product/[product_slug] 的 getStaticPaths 中以字符串形式提供所需参数 (category_slug)
这可以在 Next.js 中执行嵌套路由文件夹吗?我找不到这方面的任何信息。我在下面展示我的代码。
pages
   |-categories
       |-[category_slug]
           |-index.js     
           |-product
               |-[product_slug].js       
Run Code Online (Sandbox Code Playgroud)
我尝试向 提供硬编码值[category_slug]。这样的话就正确了吗?我也不确定。我在文档中找不到此内容。
// [product_slug].js
export async function getStaticProps({ params: { product_slug } }) {
  const product_res = await fetch(
    `${API_URL}/products/?product_slug=${product_slug}`
  ); // question mark is query slug, to find the slug in the json
  const found = await product_res.json();
  return {
    props: {
      product: found[0],
    }
  };
}
export async function getStaticPaths() {
  // Retrieve all the possbile paths
  const products_res = await fetch(`${API_URL}/products/`);
  const products = await products_res.json();
  return {
    paths: products.map((product) => ({
          params: { product_slug: product.product_slug },
        }),
    fallback: false, 
  };
}
Run Code Online (Sandbox Code Playgroud)
[product_slug]任何人都可以提供在动态路由中输入第一个动态路径的正确方法吗?
jul*_*ves 11
正如@ckoala 提到的,你只需要检索category_slug你的 中可能的[product_slug]s getStaticPaths。
根据您的路由结构,我假设每个产品都属于给定的类别。在这种情况下,您需要获取 中每个类别的所有产品getStaticPaths。
// categories/[category_slug]/product/[product_slug].js
export async function getStaticPaths() {
    // Add your logic to fetch all products by category
    return {
        paths: [
            // For each category/product combination you would have an entry like the following:
            {
                params: {
                    category_slug: 'orange'
                    product_slug: 'orange_juice',
                }
            }
        ],
        fallback: false
  };
}
Run Code Online (Sandbox Code Playgroud)
然后您getStaticProps还会期望额外的category_slug参数。
export async function getStaticProps({ params: { category_slug, product_slug } }) {
    // Add logic to fetch a single product based on `category_slug` and/or `product_slug`
    return {
        props: {
            product
        }
    };
}
Run Code Online (Sandbox Code Playgroud)
给定用作示例的条目,getStaticPaths您将能够访问以下路径:/categories/orange/product/orange_juice。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           18033 次  |  
        
|   最近记录:  |