javascript - 如何创建模式自定义以使用来自 gatsby 博客的可选字段 "featureImage"

标签 javascript reactjs graphql gatsby

我正在制作一个 Gatsby 博客作为副业。

我想在 mdx frontmatter 中使用“featureImage”可选字段。

我试图引用 https://www.gatsbyjs.com/docs/reference/graphql-data-layer/schema-customization#creating-type-definitions根据错误提示文档,但难以理解。

这是我的代码的一部分。

索引.js

import React, { useEffect } from "react";
import { graphql } from "gatsby";
import { App, ContentCard, TagsNavi, User } from "../components";
import { ContentWrapper } from "../elements";
import { useDispatch, useTag } from "../store/StoreContext";
import { ALL, SET_TAG, TAG } from "../constants";

const IndexPage = ({ location, data }) => {
  const {
    allMdx: { edges },
  } = data;

  const tag = useTag();
  const dispatch = useDispatch();

  useEffect(() => {
    const tagName = new URLSearchParams(location.search).get(TAG);
    dispatch({ type: SET_TAG, tag: tagName || ALL });
  }, [dispatch, location.search]);

  return (
    <App title="Home">
      <div>
        <ContentWrapper>
          <User />
          <TagsNavi />
          {edges
            .filter(
              (edge) => edge.node.frontmatter.tags.includes(tag) || tag === ALL
            )
            .map((edge) => {
              const { node } = edge;
              return <ContentCard key={node.slug} {...node} />;
            })}
        </ContentWrapper>
      </div>
    </App>
  );
};

export default IndexPage;

export const pageQuery = graphql`
  query AllPostsQuery {
    allMdx(sort: { fields: frontmatter___date, order: DESC }) {
      edges {
        node {
          slug
          excerpt(pruneLength: 140, truncate: true)
          frontmatter {
            date(formatString: "MMMM DD, YYYY")
            tags
            title
            featureImage {
              childImageSharp {
                gatsbyImageData
              }
            }
          }
        }
      }
    }
  }
`;

Gatsby 节点.js

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
  const typeDefs = `
    type MdxFrontmatter implements Node {
      featureImage: File
    }
  `;
  createTypes(typeDefs);
};

我试过了,当 featureImage 不存在时它可以工作。 但是,如果我有 featureImage,它就不起作用。

如何创建我想要的功能?请帮助我。

我的英语不好,所以我用了翻译,所以我的话可能有点奇怪。对不起。


Codesandbox地址在这里。 https://codesandbox.io/s/gatsby-starter-ki-demo-8fyty?file=/gatsby-node.js

在本地测试时, GraphiQL Playground 输出:“无法读取未定义的属性‘contentDigest’” 终端消息:节点 id 的错误 getNodeAndSavePathDependency 失败:未定义,因为在缓存中找不到它

警告您不能将 childImageSharp 与 undefined.undefined 一起使用 — 请改用 publicURL。此文件中查询的 childImageSharp 部分将返回 null: 未定义

浏览器控制台:警告: Prop 类型失败: Prop imageGatsbyImage 中被标记为必需,但其值为 undefined

[gatsby-plugin-image] 缺少图像属性

最佳答案

您可能会发现这个 GitHub thread有见地的。按照它,尝试使用:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions

  createTypes(`
    type Mdx implements Node {
      frontmatter: MdxFrontmatter!
    }
    type MdxFrontmatter {
      featuredImage: File @fileByRelativePath
    }
  `)
}

我在您的实现中假设的问题是,Gatsby 没有内部节点来处理您的图像,因此解析器无法找到创建 childImageSharp 的路径。这就是输出为 undefined 的原因。

其他有用的线程:


Browser console: Warning: Failed prop type: The prop image is marked as required in GatsbyImage, but its value is undefined.

这是因为您正在尝试渲染 GatsbyImage 无论是否存在,所以您没有传递任何 image Prop 。您尚未在组件中共享逻辑,但添加了一个简单的三元条件,例如:

{data.someNode.featuredImage && <GatsbyImage image={data.someNode.featuredImage} /> }

P.S:很遗憾CodeSandbox的问题,感谢您的尝试

关于javascript - 如何创建模式自定义以使用来自 gatsby 博客的可选字段 "featureImage",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69738768/

相关文章:

javascript - 如何选择最接近随机数的整数?

javascript - 处理 chart.js 中的数据重叠

css - Material UI Raised Button 在悬停时改变颜色

clojure - 嵌套级别之间具有相互依赖值的 map 规范?

ios - 所有 GraphQL 标量都以字符串形式出现 (Apollo)

javascript - 无法在 Aframe 中单击按钮时更改纹理

javascript - 是否有像条件运算符一样缩短 if 语句的语法?

javascript - React 和 Firebase : adding date to database causes listener to trigger twice?

javascript - REACT - 使用多个数组迭代 Json 对象

GraphQL - 在联合中使用不同类型的相同字段名称