NextJS和Strapi:使用一个getStaticPaths()函数获取多个API页面



NextJs和Strapi都解释了如何通过以下操作从Strapi内部的单个收集类型中提取数据:

const pages = await (await fetch(getStrapiURL("/pages"))).json();
const paths = pages.map((page) => {
// Decompose the slug that was saved in Strapi
const slugArray = page.slug.split("__");
return {
params: { slug: slugArray },
};
});
return { paths, fallback: true };

}

现在我的目标是从多个集合类型/页面中提取数据:这是我目前使用的代码:

export async function getStaticPaths() {
const [ pages, blogs ] = await Promise.all([
fetchAPI("/pages"),
fetchAPI("/blogs"),
]);
}

正如您所看到的,我使用了promise函数来同时获取多个
如何在地图功能中将这两个页面映射在一起

编辑:我这样使用使情况变得复杂

export async function getStaticPaths() {
const [pages, blogs] = await Promise.all([
fetchAPI("/pages"),
fetchAPI("/blogs"),
]);
const all = {pages, blogs}
const paths = Object.keys(all).map(a => ({params: all[a]}))
return {
paths,
fallback: true
}
}

但是,虽然你可以简单地这样使用:

export async function getStaticPaths() {
const all = await Promise.all([
fetchAPI("/pages"),
fetchAPI("/blogs"),
]);
const paths = all.map(a => ({params: a}))
return {
paths,
fallback: true
}
}

我的路由结构类似于/[category]/[id],也许这对某人有帮助:

export async function getStaticPaths() {
// menu item is like {title: 'Phones', alias: '/phones', ...}
const categoryPaths = MENU.filter(
(item) => item.prerenderCategoryItems
).map(({ alias }) => alias);
const singleProdPaths: Array<string> = [];
// collect all single-page paths
await Promise.all(
categoryPaths.map(async (categoryAlias): Promise<void> => {
const res = await fetch(
`${env.ORIGIN}/prods-json${categoryAlias}/items.json`
);
const categoryItems = await res.json();
const arrOfCategoryAliases = categoryItems.map(
// "phones/iphone-15"
(item) => `${categoryAlias}/${item.alias}`
);

singleProdPaths.push(...arrOfCategoryAliases);
})
);
return {
paths: singleProdPaths,
fallback: false,
};
}

最新更新