【问题标题】:How to display newly added image file with gatsby-image?如何使用 gatsby-image 显示新添加的图像文件?
【发布时间】:2021-03-10 08:03:55
【问题描述】:

在我的 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",
  ],

如果我在保存新图像后重新启动应用程序,一切都会正常运行

【问题讨论】:

    标签: javascript graphql gatsby gatsby-image


    【解决方案1】:

    当然,您需要刷新/重建应用程序以使用您的图像更新系统。 Gatsby 在构建/开发时编译、捆绑和处理所有资产,因此如果您添加新图像,则需要重新构建应用程序以允许 Gatsby 为该图像创建架构和节点。

    根据您的情况,您有几个选择:

    • 使用本机 img 标记并使用其他第三方依赖项(lazyloading 等)重新创建 gatsby-image 的好处。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-10
      • 2019-12-23
      • 2020-07-13
      • 2018-10-05
      • 2021-12-31
      • 1970-01-01
      • 2019-10-19
      相关资源
      最近更新 更多