假设您具有以下数据结构:
const data = {
posts: [{
id: 1,
title: "Post 1"
slug: "post-1"
}, {
id: 2,
title: "Post 2"
slug: "post-2"
}],
comments: [{
id: 1,
postId: "post-1",
text: "Comment 1 for Post 1"
}, {
id: 2,
postId: "post-1",
text: "Comment 2 for Post 1"
}, {
id: 3,
postId: "post-2",
text: "Comment 1 for Post 2"
}]
}
您具有以下路线/posts/[postId[/[commentId]
因此Next.js结构文件夹为:posts/[postId]/[commented].js
然后,您需要为此路由生成静态路径。
我的代码如下:
export async function getStaticPaths() {
const { posts, comments } = data
const paths = posts.map((post) => {
return comments
.filter((comment) => comment.postId === post.slug)
.map((comment) => {
return {
params: {
postId: post.slug,
commentId: comment.id
}
}
})
})
}
但是它不起作用。引发的错误是:
Error: Additional keys were returned from `getStaticPaths` in page "/clases/[courseId]/[lessonId]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:
return { params: { postId: ..., commentId: ... } }
Keys that need to be moved: 0, 1.
如何将数据“映射”或“循环”为正确的返回格式? 预先感谢!
答案 0 :(得分:2)
问题似乎是您从getStaticPaths
数据中返回了错误的形状:
[
[ { params: {} }, { params: {} } ],
[ { params: {} } ]
]
正确的形状是:
[
{ params: {} },
{ params: {} },
{ params: {} }
]
只需尝试一下就可以了。
export async function getStaticPaths() {
const paths = data.comments.map((comment) => {
return {
params: {
postId: comment.postId,
commentId: comment.id
}
}
});
console.log(paths);
return {
paths,
fallback: false
}
};
它生成3个网址:
是您需要的吗?
答案 1 :(得分:2)
就像@Aaron一样,问题是滤波器映射的双重数组。
dependencies {
implementation 'my.group1:my-module1:0.0.1'
implementation 'my.group2:my-module2:0.0.1'
}
jar {
from {
configurations.compileClasspath.filter { it.exists() }.collect { it.isDirectory() ? it : zipTree(it) }
}
}
Doc➡https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required