问题描述
更新:
- 哪个是由于 [category_slug]-index.js
getServerSideProps
而导致此错误的? - 我尝试在产品文件夹下执行
index.js
,它有效,这意味着 [category_slug] 哪个getServerSideprops
没问题,我说得对吗?
这是我的文件夹结构
pages
|-categories
|-[category_slug]
|-index.js
|-product
|-[product_slug].js
当我输入 [product_slug] 时会导致错误。显示:
错误:在 /categories/[category_slug]/product/[product_slug] 的 getStaticPaths 中没有以字符串形式提供必需的参数 (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",],};
}
谁能提供一个正确的方法来输入 [product_slug] 动态路径中的第一个动态路径?
解决方法
如评论中所述,您只需要在您的 category_slug
的 [product_slug]
中检索可能的 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
。