如何使用 gatsby-image 显示新添加的图像文件?

How to display newly added image file with gatsby-image?

在我的 Gatsby 应用程序中,用户可以上传保存在本地并完美显示的图片,但 gatsby-image 看不到新图片,这就是我的 Image.js 文件的样子。

我认为 graphql 数据需要以某种方式刷新,因为如果我这样做,新图像甚至不会显示 console.log(data.images) 但我该怎么做?

import React from "react"
import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"

const Image = props => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 1200) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      console.log(data.images)
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(props.filename)
      })
      if (!image) {
        return null
      }
      return (
        <Img
          alt={props.alt}
          fluid={image.node.childImageSharp.fluid}
          style={props.customStyle}
        />
      )
    }}
  />
)

export default Image

Gatsby 也能识别出添加了新文件,并在添加文件后在终端中打印出来

info added file at D:\WebsitesProjects\Portfolio\Ecommerce\images\daf27e67-01e5-4ba1-a25b-2348f4340eae.jpg
info changed file at D:\WebsitesProjects\Portfolio\Ecommerce\images\daf27e67-01e5-4ba1-a25b-2348f4340eae.jpg
success building schema - 0.421s
info Total nodes: 82, SitePage nodes: 14 (use --verbose for breakdown)
success createPages - 0.001s
success Checking for changed pages - 0.000s
success update schema - 0.026s
success onPreExtractQueries - 0.001s
success extract queries from components - 0.758s
success write out requires - 0.006s
success run static queries - 0.176s - 2/2 11.33/s
success Generating image thumbnails - 0.162s - 3/3 18.54/s

我尝试使用 gatsby-plugin-node-reload,但它似乎不起作用。这是我的 gatsby-config.js 插件

plugins: [
    `gatsby-plugin-material-ui`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `../images`),
      },
    },
    "gatsby-plugin-node-reload",
  ],

如果我在保存新图像后重新启动应用程序,一切都会完美无缺

当然,您需要refresh/rebuild应用程序用您的图像更新系统。 Gatsby 在 build/develop 时间内编译、捆绑和处理所有资产,因此如果您添加新图像,您将需要重建应用程序以允许 Gatsby 为该图像创建模式和节点。

根据您的情况,您有以下几种选择:

  • 使用原生 img 标签并使用其他第三方依赖项(lazyloading 等)重现 gatsby-image 的优势。

  • 创建一个 webhook 以在上传图像时触发重建。 Webhook 是应用程序在新事件实时发生时通知另一个应用程序的一种方式。我不推荐这种方法,因为它会导致您的应用程序在部署时崩溃。

  • 使用其他一些 SSR 框架而不是 Gatsby。