TypeError:无法读取null的属性'childImageSharp'

时间:2020-10-24 06:58:40

标签: gatsby gatsby-image

我正在尝试使用盖茨比图像,但无法读取null的属性'childImageSharp'。我找不到错误在哪里。 Topsection.js是Component下的一个组件。 image.jpg在src / images / images.jpg内部。仍然出现错误,无法解决。我已经附上了所有文件。请帮我解决。

Topsection.js

const TopSection = () => {
  const data = useStaticQuery(graphql`

   {
      featureimg: file(relativePath: { eq: "image.jpg" }) {
        childImageSharp {
          fluid(maxWidth: 60) {
            ...GatsbyImageSharpFluid
          }
        }
      }
     
    }
    
  `);
  

    return (
      
        <>
  <div className="first-post-thumbnail">
                    <a href="/best-keyboard-for-wow/">
                      
                        <Image fluid={data.featureimg.childImageSharp.fluid} />
                    
                    </a>
                  </div>

   </>
    );
};

export default TopSection;

错误:

35 | <div className="first-post-thumbnail">
  36 |   <a href="/best-keyboard-for-wow/">
  37 |     
> 38 |       <Image fluid={data.featureimg.childImageSharp.fluid} />
     | ^  39 |   
  40 |   </a>
  41 | </div>

配置

/**
 * Configure your Gatsby site with this file.
 *
 * See: https://www.gatsbyjs.com/docs/gatsby-config/
 */

module.exports = {
  /* Your site config here */
  siteMetadata: {
    title: ``,
    description: ``,
    author: ``,
  },
  plugins: [
  `gatsby-plugin-react-helmet`,
  `gatsby-transformer-sharp`, `gatsby-plugin-sharp`,

  
  {

    
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },

    resolve: `gatsby-plugin-prefetch-google-fonts`,
    options: {
      fonts: [
        {
          family: `Poppins`,
          variants: [`200`,`300`,`400`,`500`,`600`,`700`, `900`]
        },
      ],
    },

    
  },
],
}

3 个答案:

答案 0 :(得分:0)

假设您已正确设置文件系统,并且GraphQL可以使用该图像。

尝试:

import Img from "gatsby-image"
// other imports

const TopSection = () => {
  const data = useStaticQuery(graphql`
      query {
          featureimg: file(relativePath: { eq: "/images/image.jpg" }) {
              childImageSharp {
                  fluid(maxWidth: 60) {
                      ...GatsbyImageSharpFluid
                  }
              }
          }
      }
  `);

  return <div className="first-post-thumbnail">
    <a href="/best-keyboard-for-wow/">
      <Img fluid={data.featureimg.childImageSharp.fluid} />
    </a>
  </div>;
};

export default TopSection;

文件节点的relativePath字段相对于您在gatsby-source-filesystem中指定的目录。

我建议使用<Link>组件而不是本机<a>(锚点)进行内部导航:

    <Link to="/best-keyboard-for-wow/">

在GraphQL游乐场(localhost:8000/___graphql)中检查查询,以检查拼写和结果。

答案 1 :(得分:0)

Clearing the cache 对我来说是成功的(除了删除 package-lock.json 并重新运行 npm install):

gatsby clean

答案 2 :(得分:0)

清理项目并重新运行“npm install”工作

npm run clean

然后

npm install