如何在使用getStaticPaths的类别中使用嵌套的getStaticPath来制作post文件?(使用API)



〔Next.js〕使用无头CMS WordPress和插件[WPGraphQL],通过调用getStaticPaths中的API,我能够创建一个类别列表。

src
--pages
----category
------[slug.tsx] 
--------page
----------[pageNo.tsx]

以下getStaticPaths在[slug].tsx 中进行了描述

export async function getStaticPaths () {
const allPosts = await GET_ALL_CATEGORIRS_SLUG ();
return {
paths: paths:
allPosts.edges.map (({node}) => `/category/${node.slug}`) ||
[],
fallback: true,
};
}

以下getStaticPaths在[pageNo].tsx 中进行了描述

export async function getStaticPaths() {
const totalCount = await GET_TOTAL_POST_COUNT(currentCategorySlug);
const totalPostsCount = totalCount.pageInfo.offsetPagination.total ?? 0;
const pagesCount = Math.ceil(
(totalPostsCount - PER_PAGE_FIRST) / PER_PAGE_REST + 1
);
const paths = new Array(pagesCount).fill("").map((_, index) => ({
params: {
pageNo: (index + 1).toString(),
},
}));
return {
paths: [...paths],
fallback: true,
};
}

但是,除非清除currentCategorySlug,否则这是不起作用的。

如何获取当前父类别?

我不能在这里使用useRouter,所以请告诉我是否有办法获得currentCategorySlug或其他东西。或者你在某个地方使用useRouter?

这是一个有点粗糙的代码,但我已经解决了它,所以我将描述它。

export async function getStaticPaths() {
const allCategoryAndPosts = await GET_ALL_CATEGORY_AND_POSTS();
var paths = new Array();
allCategoryAndPosts.edges.map(({ node }) => {
const totalPostsCount = node.posts.pageInfo.offsetPagination.total ?? 0;
const pagesCount = Math.ceil(
(totalPostsCount - PER_PAGE_FIRST) / PER_PAGE_REST + 1
);
for (let index = 1; index <= pagesCount; index++) {
paths.push(`/category/${node.slug}/page/${index}` || []);
}
});
return {
paths: [...paths],
fallback: true,
};
}

最新更新