我希望有人遇到了类似的事情,并能给我一些正确的方向的建议。
我正在使用gatsby创建一个博客,其中的内容来自于棱镜。每篇博客文章都有一个作者和标签,通过棱镜内容关系与它们相关。我的目标是通过gatsby-node为作者和标签页面动态创建页面,这些页面还包括相关博客文章的分页。不幸的是,Prismic似乎不能创建双向的关系,所以我必须通过在我的allPrismicBlog上对author uid进行graphql查询来查找相关的博客帖子。
我尝试完成的urls示例: myblog.com/author/author-name/ myblog.com/author/author-name/2
我的gatsby节点中包含以下内容:
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions;
const authors = await graphql(`
{
allPrismicAuthor {
edges {
node {
uid
}
}
}
}
`);
authors.data.allPrismicAuthor.edges.forEach(edge => {
const authorUid = edge.node.uid;
const authorPosts = graphql(`
{
allPrismicBlog(filter: { data: { author: { uid: { eq: ${authorUid} } } } }) {
edges {
node {
uid
}
}
}
`);
const numAuthorPages = Math.ceil(authorPosts.length / 2);
Array.from({ length: numAuthorPages }).forEach((_, i) =>
createPage({
path: i === 0 ? `/author/${authorUid}` : `/author/${authorUid}/${i + 1}`,
component: path.resolve('./src/templates/author.jsx'),
context: {
limit: 2,
skip: i * 2,
numPages,
currentPage: i + 1,
uid: authorUid,
},
}),
);
});
};
我收到错误TypeError: Cannot read property 'page' of undefined
我不确定我在这里尝试做的是不是正确的方向,或者我是否错过了一些重要的东西。任何帮助都将不胜感激。
发布于 2019-10-03 15:12:39
上面的代码没有显示任何页面变量。
也许这样可以帮助我从整体上看到代码?
也许您事先忘记了定义page变量
发布于 2019-10-04 16:43:50
找出了一个解决方案,并想在这里分享,以防其他人在未来遇到类似的事情。
我没有尝试使用作者的uid查询博客文章,也没有处理这两个查询的异步特性,而是过滤blogList并基于它创建页面。可能有几种方法可以在重构期间改进这段代码,但我想分享我的工作成果。
const blogList = await graphql(`
{
allPrismicBlog(sort: { fields: [data___blog_post_date], order: DESC }, limit: 1000) {
edges {
node {
uid
data {
author {
uid
}
tag {
uid
}
}
}
}
}
}
`);
const posts = blogList.data.allPrismicBlog.edges;
const authors = await graphql(`
{
allPrismicAuthor {
edges {
node {
uid
}
}
}
}
`);
authors.data.allPrismicAuthor.edges.forEach(edge => {
const authorUid = edge.node.uid;
const authorBlogs = posts.filter(post => post.node.data.author.uid === authorUid);
const numAuthorPages = Math.ceil(authorBlogs.length / 1);
for (let i = 0; i <= numAuthorPages; i++) {
createPage({
path: i === 0 ? `/author/${authorUid}` : `/author/${authorUid}/${i + 1}`,
component: pageTemplates.Author,
context: {
limit: 1,
skip: i * 1,
numPages,
currentPage: i + 1,
uid: authorUid,
},
});
}
});
https://stackoverflow.com/questions/58221403
复制相似问题