Graphql 如何在不迭代的情况下从数组中访问特定元素?

Graphql 如何在不迭代的情况下从数组中访问特定元素?,graphql,gatsby,graphql-js,gatsby-image,Graphql,Gatsby,Graphql Js,Gatsby Image,我有以下文件夹结构 /images /images/pic1.jpg /images/pic2.jpg 使用以下GraphQL查询时 query MyQuery1 { file(sourceInstanceName: {eq: "images"}, name: {eq: "pic1"}) { name publicURL } } 可以使用类似的方法访问结果。到目前为止还不错 但现在我想用一个查询从该文件夹中检索多个图像。因此,我提出了以下建议: query { a

我有以下文件夹结构

/images
/images/pic1.jpg
/images/pic2.jpg
使用以下GraphQL查询时

query MyQuery1 {
  file(sourceInstanceName: {eq: "images"}, name: {eq: "pic1"}) {
    name
    publicURL
  }
}
可以使用类似
的方法访问结果。到目前为止还不错

但现在我想用一个查询从该文件夹中检索多个图像。因此,我提出了以下建议:

query {
  allFile(
    filter: {
      sourceInstanceName: { eq: "images" }
      name: { in: ["pic1", "pic2"] }
    }
  ) {
    nodes {
      name
      publicURL
    }
  }
}
太好了!但是我现在如何访问其中一个图像而不必使用
map
或迭代结果呢

我在找这样的东西,当然不行:

这样的事情也不会发生:


我想使用
gatsby image
来优化和调整图像大小。这就是为什么我选择GraphQL方式而不是直接导入。我走错方向了吗

我自己想出来的。我不知道一个人可以把东西连在一起。这对我有用

query {
  imageOne: file(sourceInstanceName: {eq: "images"}, relativePath: {eq: "pic1.jpg"}) {
    id
    childImageSharp {
      fixed(width: 30) {
        base64
        tracedSVG
        aspectRatio
        width
        height
        src
        srcSet
        srcWebp
        srcSetWebp
        originalName
      }
    }
  }
  imageTwo: file(sourceInstanceName: {eq: "images"}, relativePath: {eq: "pic2.jpg"}) {
    id
    childImageSharp {
      fixed(width: 30) {
        base64
        tracedSVG
        aspectRatio
        width
        height
        src
        srcSet
        srcWebp
        srcSetWebp
        originalName
      }
    }
  }
}
然后像这样访问它:

<Img fixed={data.imageOne.childImageSharp.fixed} alt="" />

OP回答了他们自己的问题,但这里有另一种方法:使用

<Img fixed={data.imageTwo.childImageSharp.fixed} alt="" />
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`, <<== gets filtered by sourceInstanceName: ..
    path: `${__dirname}/src/images/`,
  },
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
const Index = (props) => {
  const { data: { allFile: { edges } } } = props;

  const heroImage = edges.filter
    (el => el.node.childImageSharp.fluid.originalName === "heroImage.png")
      [0].node.childImageSharp.fluid;
  // ...
}

export const query = graphql`
{
  allFile(filter: {
    extension: {eq: "png"},
    sourceInstanceName: {eq: "images"}},
    sort: {fields: [childImageSharp___fluid___originalName], order: ASC})
  {
    edges {
      node {
      childImageSharp {
          fluid(maxWidth: 300, quality: 50) {
            originalName
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
}
`;