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

我有以下文件夹结构

/images
/images/pic1.jpg
/images/pic2.jpg

使用以下GraphQL查询时。

query MyQuery1 {
  file(sourceInstanceName: {eq: "images"},name: {eq: "pic1"}) {
    name
    publicURL
  }
}

可以使用<img src={data.file.publicUrl} alt="" />之类的东西来访问结果。到目前为止,一切都很好。

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

query {
  allFile(
    filter: {
      sourceInstanceName: { eq: "images" }
      name: { in: ["pic1","pic2"] }
    }
  ) {
    nodes {
      name
      publicURL
    }
  }
}

太好了!但是,现在如何不使用map或遍历结果而访问那些图像之一?

我正在寻找类似的东西,但那当然不起作用:

<img src={data.file.publicUrl name.eq="pic1"} alt="pic1"/>

Nor不会这样:

<img src={data.allFile.nodes.0.publicUrl} alt="pic1" />

我想使用gatsby-image来优化图像并调整其大小。这就是为什么我选择GraphQL方法而不是直接导入的原因。我走错了路吗?

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

我自己弄清楚了。我不知道一个人可以链接在一起。这对我有用。

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="" />

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

P.S:这是gatsby-config.js

中的相对部分
{
  resolve: `gatsby-source-filesystem`,options: {
    name: `images`,<<== gets filtered by sourceInstanceName: ..
    path: `${__dirname}/src/images/`,},`gatsby-transformer-sharp`,`gatsby-plugin-sharp`,
,

OP回答了他们自己的问题,但这是另一种方法:使用Array.prototype.filter

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
          }
        }
      }
    }
  }
}
`;

本文链接:https://www.f2er.com/2992595.html

大家都在问