微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Gatsby.js

如何解决如何在 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 和数据,以上都不再起作用。这是我在转换后的 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',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`,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 中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。