Next.js 嵌套动态文件夹路由

Next.js nested dynamic folder routing

更新:

  1. 由于 [category_slug]-index.js 而导致此错误 getServerSideProps?
  2. 我尝试在产品文件夹下执行 index.js,它有效,意味着它可以与 [category_slug] 和 getServerSideprops,对吗?

这是我的文件夹结构

pages
   |-categories
       |-[category_slug]
           |-index.js     
           |-product
               |-[product_slug].js       

输入[product_slug]时出错。显示:

Error: A required parameter (category_slug) was not provided as a string in getStaticPaths for /categories/[category_slug]/product/[product_slug]

这可以在 Next.js 中做嵌套路由文件夹吗?我找不到这方面的任何信息。 我在下面展示了我的代码。

// [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, 
  };
}

我试图向 [category_slug] 提供硬编码值。这样做对吗?我也不确定。我在文档中找不到这个。

export async function getStaticProps({ params: { product_slug } }) {
  const product_res = await fetch(
    `${API_URL}/products/?product_slug=orange_juice`
  ); 

  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: [
      {
        params: {
          product_slug:
            "categories/orange/product/orange_juice",
        },
      },
    ],
    fallback: false,
  };
}

任何人都可以提供在 [product_slug] 动态路由中输入第一个动态路径的正确方法吗?

作为 ,您只需要在 [product_slug]getStaticPaths.

中检索可能的 category_slug

我假设,根据您的路由结构,每个产品都属于一个给定的类别。在这种情况下,您需要获取 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
  };
}

您的 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
        }
    };
}

鉴于 getStaticPaths 中用作示例的条目,您将能够访问以下路径:/categories/orange/product/orange_juice.