如何使用字段作为来自一个graphql查询的过滤器,以在单独的查询中获得真实的图像?

问题描述

在mongo数据库中,我有两个graphql源,一个用于流体图像,一个用于字符。我正在将字符映射到页面,我需要使用字符名称(“ allMongodbMobileLegendsdevChamps”中的名称字段)作为过滤器(可能使用originalName过滤器)来查找流畅的img。所以我有这样的东西

query MyQuery {
  allMongodbMobileLegendsdevChamps {
    nodes {
      name
    }
  }
  allImageSharp(filter: {fluid: {originalName: {eq: "characterName.jpg"}}}) {
    nodes {
      fluid {
        ...allImageSharpFluid
      }
    }
  }
}
const Index = ({ data }) => {
  const {
    allMongodbMobileLegendsdevChamps: { nodes: champs },allImageSharp: { nodes: fluid },} = data
  return (
    <section className={grid}>
      {champs.map(champ => {
        return (
          <Link to={`/champ/${champ.name}`}>
            <Image fluid={fluid.fluid} />
            <h3>{champ.name}</h3>
          </Link>
        )
      })}
    </section>
  )
}

如果我不使用graphql,则只需将图像中的src设置为“ champ.name”,如下所示:

<Image src = `/path/to/img/${champ.name}.jpg` />

如何使用champ.name过滤图像查询?我应该使用Apollo这样的东西吗?

解决方法

这是Gatsby,目前无法实现,因为您无法将变量传递给GH问题https://github.com/gatsbyjs/gatsby/issues/10482

假设可以传递变量,那么我将所有字符作为页面查询,使我可以从props重新构造名称,然后进行静态查询,并将名称作为过滤器传递给

,

我使用了此解决方案,并对其进行了稍微的调整以满足自己的需求:Variables in graphQL queries

在父组件中,我映射了所有冠军,并为每个子组件创建了一个子组件,并向其传递了冠军名称。

在子组件中,我有一个变量名,该变量通过使用find方法将冠军名称与图像relativePath匹配来存储要显示的图像的正确节点(图像的确切名称与冠军)。然后,我调用函数renderImage,该函数使用变量“名称”,并在node.childImageSharp.fluid中找到流体图像,并使用正确的流体图像位置创建我的图像组件。

import React from "react"
import { useStaticQuery,graphql } from "gatsby"
import { displayName } from "../../utils/championName"
import * as S from "../styled/ChampionGridCard"

const renderImage = file => {
  return <S.ChampionImage fluid={file.node.childImageSharp.fluid} />
}

const ChampionGridCard = props => {
  const data = useStaticQuery(graphql`
    {
      allFile(filter: { sourceInstanceName: { eq: "champImages" } }) {
        edges {
          node {
            extension
            relativePath
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `)

  const name = data.allFile.edges.find(
    image => image.node.relativePath === `ssbu/${props.champName}.jpg`
  )

  return (
    <S.ChampionGridCard to={`/champ/${props.champName}`}>
      <S.ChampionImageWrapper>{renderImage(name)}</S.ChampionImageWrapper>
    </S.ChampionGridCard>
  )
}

export default ChampionGridCard