关于运行多个查询的Gatsby技巧(GraphQL别名)

发布于:2021-02-04 09:50:20

0

603

0

图形 jamstack Gatsby React

假设您要基于一个参数或条件在一个页面中获取特定数据,而该参数或条件不能使用一个查询运行,因为您不能使用不同的条件或参数查询同一字段。一种方法是使用GraphQL别名,您可以使用它将返回的数据集重命名为任何您想要的名称。

示例

export const query = graphql`
 query {
   post: allMarkdownRemark(
     limit: 3
     sort: { order: DESC, fields: [frontmatter___date] }
     filter: { frontmatter: { type: { ne: "portfolio" } } }
   ) {
     edges {
       node {
         timeToRead
         frontmatter {
           title
           path
           date(formatString: "DD MMMM YYYY")
           summary
           images
           tags
           type
         }
       }
     }
   }
   portfolio: allMarkdownRemark(
     sort: { order: DESC, fields: [frontmatter___date] }
     filter: { frontmatter: { type: { eq: "portfolio" } } }
   ) {
     edges {
       node {
         frontmatter {
           title
           path
           images
           tags
           type
         }
       }
     }
   }
   siteMetaData: site {
     siteMetadata {
       title
     }
   }
 }
`;

查看上面的示例,我们可以看到我所做的查询将返回多个数据集,方法是为其提供一个别名,该别名允许我使用不同的参数和条件运行多个查询,以获得您在屏幕截图中看到的所需的特定数据对象。