如何使用带 Gatsby.js 的地图函数正确渲染图像

How to properly render images using a map function with Gatsby.js

此应用程序最初是使用 React 构建的,但我们决定将所有内容转换过来并使用 Gatsbyjs。我是 Gatsby 的新手,我正在尝试使用艺术家数据正确渲染我的图像。 以下是这部分数据最初的构建方式:

const images = [
  AngelAndJaamiHeadshot,
  BillyHawkinsHeadshot,
  BostonWellsHeadshot,
  BreanahAlvizHeadshot,
  CarloCollantesHeadshot,
  CarloDarangHeadshot,
  ChrisLumbaHeadshot,
  ChrisMartinHeadshot,
  CJDelaVegaHeadshot,
  CyeBongalosHeadshot,
  DanielKimHeadshot,
  DavidDarkieSimmonsHeadshot,
  // DavidDiosoHeadshot,
  DavidSlaneyHeadshot,
  DavinLawsonHeadshot,
  DevinHeadshot,
  DustinYuHeadshot,
  EmilyRowanHeadshot,
  HonrieDualanHeadhot,
  HughAparenteHeadshot,
  JaamiWaaliVillalobosHeadshot,
  JeremyBorjaHeadshot,
  JonathanSisonHeadshot,
  JordanBautistaHeadshot,
  JordanRileyHeadshot,
  JuliaKestnerHeadshot,
  JustinArcegaHeadshot,
  KaitlynSungHeadshot,
  KaylarPrieteHeadshot,
  KeyanaReedHeadshot,
  KikoJamesHeadshot,
  KirstieAndJeremyHeadshot,
  KirstieHeadshot,
  KJEstudilloHeadshot,
  LarkinPoyntonHeadshot,
  MitchVillarealHeadhsot,
  MoanaRakanaceHeadshot,
  NoelleFrancoHeadshot,
  PhuongLeHeadshot,
  SamMooreHeadshot,
  TonyRayHeadshot,
  TracySeilerHeadshot,
  TrishaOcampoHeadshot,
  YutaNakamuraHeadshot,
  defaultHeadshot,
]

export const buildArtistsData = (artists) => {
  return artists.map((artist, idx) => {
    return {
      ...artist,
      imageUrl:
        idx >= 43
          ? defaultHeadshot
          : images[`${artist.firstName}${artist.lastName}Headshot`],
    }
  })
}

这就是它在我的艺术家组件中的使用方式:

const ArtistsPage = () => {
 const artists = buildArtistsData(ARTISTS)

...

<div className={classes.flexContainer}>
          {artists
            .map(
              (
                { city, currentTeam, firstName, lastName, imageUrl },
                idx: number
              ) => {
                return (
                  <div className={classes.flexItem} key={idx}>
                    <img
                      className={classes.artistCardImg}
                      src={imageUrl}
                      alt='artist-image'
                    />
                    <div className={classes.artistCardName}>
                      {`${firstName} ${lastName}`.toUpperCase()}
                    </div>
                    <div className={classes.artistCardText}>{city}</div>
                    <div className={classes.artistCardText}>{currentTeam}</div>
                  </div>
                )
              }
            )}
        </div>

但现在我正在使用 Gatsbyjs,上面的数据 none 将不再起作用。这是我在转换后的 Gatsbyjs 页面上使用的内容:

import React from 'react'
import PropTypes from 'prop-types'
import { StaticImage } from 'gatsby-plugin-image'
import Img from 'gatsby-image'
import { graphql } from 'gatsby'

import { useStyles } from './styles'

const ArtistsPage = ({ data }) => {
  console.log(data)
  const classes = useStyles()
  // const { images } = props

  return (
    <section>
      <article className={classes.artistsContainer}>
        <div className={classes.flexContainer}>
          {data.allArtistsJson.edges.map(({ node }, idx) => {
            return (
              <div className={classes.flexItem} key={idx}>
                <div>
                  {images.map((img, idx) => (
                    <Img
                      key={idx}
                      fluid={img.node.childImageSharp.fluid}
                    />
                  ))}
                </div>
                <div className={classes.artistCardName}>
                  {`${node.firstName} ${node.lastName}`.toUpperCase()}
                </div>
                <div className={classes.artistCardText}>{node.city}</div>
                <div className={classes.artistCardText}>{node.currentTeam}</div>
              </div>
            )
          })}
        </div>
      </article>
    </section>
  )
}
export const pageQuery = graphql`
  query {
    headshots: allFile(filter: { absolutePath: { regex: "/headshots/" } }) {
      edges {
        node {
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

ArtistsPage.propTypes = {
  firstName: PropTypes.string,
  lastName: PropTypes.string,
  currentTeam: PropTypes.string,
  headshots: PropTypes.string,
  dropdown: PropTypes.string,
  data: PropTypes.array,
  images: PropTypes.string,
}

export default ArtistsPage

我试图将图像数据作为道具使用 const { image } = props - 但这会引发错误,所以我真的很困惑什么以及如何映射它以将我的图像拉入正确的艺术家。

还有我的config.js文件供参考:

const path = require('path')

module.exports = {
  siteMetadata: {
    title: 'Platform Showcase',
  },
  plugins: [
    'gatsby-plugin-gatsby-cloud',
    'gatsby-plugin-image',
    // {
    //   resolve: "gatsby-plugin-google-analytics",
    //   options: {
    //     trackingId: "",
    //   },
    // },
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-sitemap',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        icon: 'src/images/icon.png',
      },
    },
    'gatsby-plugin-mdx',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: './src/images/',
      },
      __key: 'images',
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `headshots`,
        path: `${__dirname}/src/images/artists/headshots`,
      },
      __key: 'headshots',
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: './src/pages/',
      },
      __key: 'pages',
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: ['material icons', 'roboto:300,400,500,700'],
      },
    },
    `gatsby-theme-material-ui`,
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/data/`,
      },
    },
    {
      resolve: 'gatsby-plugin-root-import',
      options: {
        src: path.join(__dirname, 'src'),
        containers: path.join(__dirname, 'src/containers'),
        images: path.join(__dirname, 'src/images'),
      },
    },
  ],
}

如果有人愿意提供任何帮助,我们将不胜感激。

使用页面查询时,您的数据始终在 props.data 下,因此您的嵌套应如下所示:

      {data.headshots.edges.map(({ node }, idx) => {
        return (
          <div className={classes.flexItem} key={idx}>
            <Img fluid={node.childImageSharp.fluid} />
          </div>
        )
      })}

注意:我假设您的 GraphQL 查询正确检索了数据。在 localhost:8000/___graphql 测试它并根据需要调整你的文件系统

每个图像都是 node 本身(根据查询结构),因此,由于您的查询将 allFile 别名为 headshots,因此您的数据存储在 props.data.headshots.