【发布时间】:2021-05-05 09:25:06
【问题描述】:
更新:
- 导致这个错误的原因是 [category_slug]-index.js 那
getServerSideProps? - 我尝试在产品文件夹下进行
index.js,它可以工作,这意味着它可以与getServerSideprops的[category_slug] 配合使用,对吗?
这是我的文件夹结构
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] 动态路由中输入第一个动态路径的正确方法?
【问题讨论】:
-
在我看来,您还需要在 [product_slug].js 中的 getStaticPaths() 中获取可能的 [category_slugs]。就像错误所说:“(category_slug)未提供”
-
@ckoala 是的,我为此尝试了硬编码。它仍然返回相同的错误。我想我的方式不正确??我已经更新了帖子。
-
我发现您的 [category_slug] 目录中没有
index.js。您应该尝试在那里获取所有可能的路径/ slug。我还发现这篇文章很有帮助:stackoverflow.com/questions/57648690/… -
感谢您提供此信息。但这与我的情况有点不同。我猜 nextjs 在构建静态文件期间找不到我的 [category_slug] 路径名,因此导致错误。在您分享的帖子中,没有像我这种情况的嵌套动态文件夹。
标签: javascript next.js nested-routes dynamic-routing