Nextjs嵌套动态文件夹路由

更新:

  1. 导致此错误的原因是[CATEGORY_Slug]-index.jsgetServerSideProps
  2. 我试着在产品文件夹下做index.js,它起作用了,意思是它可以与getServerSideprops的[CATEGORY_Slug]一起使用,对吗?

这是我的文件夹结构

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

当我输入[PRODUCT_SLUG]时会导致错误。正在显示:

错误:未在/categories/[category_slug]/product/[product_slug]

的getStaticPath中以字符串形式提供必需的参数(CATEGORY_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]动态路由中输入第一个动态路径?


解决方案

AS@ckoala mentioned您只需在[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

相关文章