sak*_*lan 9 javascript reactjs next.js
在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",
};
}
Run Code Online (Sandbox Code Playgroud)
我通过他们的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
};
}
Run Code Online (Sandbox Code Playgroud)
我想保留像 /blog/:slug 这样的 url,我不想包含 id。当我已经在 getStaticPaths 中获取所有帖子时,如何访问 getStaticProps 中的帖子 id 以避免通过 slug 获取?
小智 1
您可以通过 slug 过滤 API 响应以获得相同的结果
const res = await fetch(`http://localhost:1337/api/posts?filters[slug][$eq]${slug}`);
Run Code Online (Sandbox Code Playgroud)
这将产生您想要的结果
| 归档时间: |
|
| 查看次数: |
2992 次 |
| 最近记录: |