首页 > 解决方案 > 在分组的 graphql 查询中访问 Frontmatter 元素

问题描述

我试图从类别中最新帖子的前端返回特色图像。

这是我目前编写的 graphql 查询:

query catList {
        allMdx(sort: { fields: frontmatter___date, order: DESC }) {
          group(field: frontmatter___themes, limit: 1) {
            fieldValue
            totalCount
            nodes {
              frontmatter {
                featuredImage {
                  childImageSharp {
                    fixed(width: 400, height: 400) {
                      ...GatsbyImageSharpFixed
                    }
                  }
                }
              }
            }
          }
        }
      }

该查询在 graphql 编辑器中返回了我想要的内容,但是当我尝试访问组件中的 featuresImage 时,我收到一个错误:

“TypeError:无法读取未定义的属性‘featuredImage’”

以下是页面和组件的完整代码:

const CatPage = () => (
  <StaticQuery
    query={graphql`
      query themeList {
        allMdx(sort: { fields: frontmatter___date, order: DESC }) {
          group(field: frontmatter___themes, limit: 1) {
            fieldValue
            totalCount
            nodes {
              frontmatter {
                featuredImage {
                  childImageSharp {
                    fixed(width: 400, height: 400) {
                      ...GatsbyImageSharpFixed
                    }
                  }
                }
              }
            }
          }
        }
      }
    `}
    render={data => (
      <Layout>
        <Gallery>
          {data.allMdx.group.map(theme => (
            <GalleryCard to={theme.fieldValue} title={theme.fieldValue}>
              <Img
                fixed={
                  theme.nodes.frontmatter.featuredImage.childImageSharp.fixed
                }
              />
            </GalleryCard>
          ))}
        </Gallery>
      </Layout>
    )}
  />
)

这里的目标是让每个类别的最新帖子中的特色图片成为该类别的封面图片,但我在渲染图片时遇到了困难!

标签: graphqlgatsbysharp

解决方案


推荐阅读