0

我希望有人遇到过类似的事情,可以给我一些正确方向的建议。

我正在使用 gatsby 构建一个博客,其中包含从 Prismic 中提取的内容。每篇博文都有一个作者和标签,通过 Prismic 内容关系与之相关。我的目标是通过 gatsby-node 为作者和标签页面动态创建页面,其中还包括相关博客文章的分页。不幸的是,Prismic 似乎并没有建立双向关系,所以我必须通过对我的 allPrismicBlog 过滤作者 uid 进行 graphql 查询来查找相关的博客文章。

我要完成的网址示例: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

我不确定我在这里尝试做的是正确的方向,还是我错过了一些重要的事情。任何帮助将不胜感激。

4

2 回答 2

0

上面的代码没有显示任何页面变量。

也许这样可以帮助我能够看到整个代码?

也许您忘记事先定义页面变量

于 2019-10-03T15:12:39.167 回答
0

想出了一个解决方案,并想在这里分享,以防其他人将来遇到类似的事情。

而不是尝试使用作者 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,
        },
      });
    }
  });
于 2019-10-04T16:43:49.997 回答