【发布时间】:2022-05-05 00:39:56
【问题描述】:
在 SingleBlogPost.jsx 我有:
export async function getStaticPaths() {
const res = await fetch("http://localhost:1337/api/posts");
let { data } = await res.json();
const paths = data.map((data) => ({
params: { slug: data.attributes.slug },
}));
return {
paths,
fallback: "blocking",
};
}
我通过他们的 slug 生成博客页面。 但是在 getStaticProps 中,我需要通过 slug 获取单个帖子,但我想通过 id 来获取。
export async function getStaticProps(context) {
console.log("context", context);
const { slug } = context.params;
console.log("slug is:", slug);
const res = await fetch("http://localhost:1337/api/posts");
const { data } = await res.json();
return {
props: {
data,
},
revalidate: 10, // In seconds
};
}
我想保留像 /blog/:slug 这样的 url,我不想包含 id。在 url 中。当我已经获取 getStaticPaths 中的所有帖子时,如何访问 getStaticProps 中的帖子 ID 以避免通过 slug 获取?
【问题讨论】:
-
看看这个帖子,一些有用的答案贴在here
标签: javascript reactjs next.js