6

更新:

  1. 由于 [category_slug]-index.js 导致此错误的原因是getServerSideProps什么?
  2. 我试图index.js在产品文件夹下做,它有效,意味着它可以与 [category_slug] which 一起使用getServerSideprops,对吗?

这是我的文件夹结构

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

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

错误:所需参数 (category_slug) 未在 /categories/[category_slug]/product/[product_slug] 的 getStaticPaths 中作为字符串提供

这可以在 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] 动态路由中输入第一个动态路径的正确方法?

4

1 回答 1

4

正如@ckoala 提到的,你只需要category_slug在你[product_slug]的 's 中检索可能的 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
  };
}

然后,您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.

于 2021-02-03T21:45:15.873 回答