过滤器获取静态路径Nextjs



如何仅从getStaticPaths返回筛选后的路径?

这会返回整个帖子

export async function getStaticPaths() {
const { data } = await axios.get(`${url}/category`, config);
const paths = data.map((post) => {

return {
params: { postId: post.id },
};

});

return {
paths,
fallback: false
}
}

这是我重试的

export async function getStaticPaths() {
const { data } = await axios.get(`${url}/category`, config);
const paths = data.filter((post) => {
if (post.isActive) {
return { params: { postId: post.id } }
}
})
return {
paths,
fallback: false
}
}

错误消息

> Build error occurred
Error: Additional keys were returned from `getStaticPaths` in page "/product/[packageAlias]". URL Parameters intended for this dynamic route must be nested under the `params` key,

filter方法在过滤后将返回相同的对象格式,因此在filter之后需要map,可以使用flatMap方法同时执行这两项操作。

const paths = data.flatMap((post) => {
return post.isActive ? [{ params: { postId: post.id } }] : [];
})

相关内容

  • 没有找到相关文章

最新更新