微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决TypeError:无法读取null的属性'childImageSharp'

我正在尝试使用盖茨比图像,但无法读取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`]
        },],}

解决方法

假设您已正确设置文件系统,并且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)中检查查询,以检查拼写和结果。

,

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

gatsby clean

,

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

npm run clean

然后

npm install

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。