如何使用 gatsby-source-unsplash 在 gatsby 中加载 unsplash 图像

how load unsplash images in gatsby using gatsby-source-unsplash

我正在尝试使用 gatsby-source-unsplash 和 gatsby-plugin-remote-images 从 unsplash 加载图像 我的配置:

gatsby.config.js:

  {
      resolve: `gatsby-source-unsplash`,
      options: {
        appId: `${process.env.GATSBY_API_KEY}`,
        collections: [
          `70643713`
        ],
        // optional: will only get page 1, so increase this count to include > 10 photos
        perPage: `10`
      },
    }

我得到了数据,但是在尝试使用 GatsbyImage 加载图像时 url 我得到了“undefine”

var nodx = data.allUnsplashPhoto.edges;

     return (
        <div>
            {
                nodx.map(item =>{
                    var current = item.node.urls.small;
                    console.log(current);
                    return <GatsbyImage key={item.node.id} image={current} />
                })
            }
        </div>

我误解了你的目标。现在有了新提供的数据:

gatsby-source-unsplash 只获取 Unsplash 图片集的数据,但不对其进行处理(甚至不下载)所以你必须使用 img 标签引用它,而不是 GatsbyImage(来自 v3)或 Img(来自 v2)个组件。这是因为 Gatsby 需要解析、转换和处理所有图像以创建将由 GatsbyImage 组件使用的 GraphQL 节点。 URL和一些数据不能直接使用,只能用标准的img标签引用。

关于gatsby-plugin-remote-images,需要像这样使用:

{
      resolve: `gatsby-plugin-remote-images`,
      options: {
        nodeType: 'UnsplashPhoto',
        imagePath: 'nodes[].urls',
        name:'allItemImage',
      },

注意:您在 nodeType

中有错字

这是因为,如果集合是 public 并且环境变量正在检索有效值,GraphQL 将拦截并创建节点,特别是 allUnsplashPhoto 节点。允许您:

allUnsplashPhoto {
  edges {
    node {
      id
      user {
        id
        name
      }
      urls {
        full
        regular
        small
      }
      description
      created_at
    }
  }
}

该节点将使用数组表示法传递给 gatsby-plugin-remote-images,创建有效的 GraphQL 节点以与 GatsbyImageImg 组件一起使用:

allMyNodes {
  nodes {
    localImage {
      childImageSharp {
        fluid(maxWidth: 400, maxHeight: 250) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }
}

但是,我不确定您是否必须创建某种类型的异步文件以避免将 null 数据传递给 gatsby-plugin-remote-images 插件。如果是这种情况,您可能需要创建一个基于 Unsplash API endpoints 的异步请求来获取照片数组并将其发送到 imagePath 节点。