【问题标题】:TypeError: Cannot read property 'fixed' of nullTypeError:无法读取 null 的“固定”属性
【发布时间】:2019-02-20 00:59:27
【问题描述】:

我收到此错误消息:TypeError: Cannot read property 'fixed' of null。

该项目包括 Javascript、Reactjs、Gatsbyjs 和 Contentful。

错误代码部分:

  3 | import { styles } from '../../utils'
  4 | import Img from 'gatsby-image'
  5 | 
> 6 | export default function Product({ product }) {
  7 |   const { name, price, ingredients } = product;
  8 |   const { fixed } = product.img;
  9 | 

现有代码:

import React from 'react'
import styled from 'styled-components'
import { styles } from '../../utils'
import Img from 'gatsby-image'

export default function Product({ product }) {
  const { name, price, ingredients } = product;
  const { fixed } = product.img;

  return (
    <ProductWrapper>
      <Img fixed={fixed} className="img" />
      <div className="text">
        <div className="product-content">
          <h3 className="name">{name}</h3>
          <h3 className="price">${price}</h3>
        </div>
        <p className="info">{ingredients}</p>
      </div>
    </ProductWrapper>
  )
}

Fixed 在 Menu.js 中定义

                    img {
                      fixed(width: 150, height: 150) {                            ...GatsbyContentfulFixed_tracedSVG

在花了很多时间寻找解决方案后,我决定寻求任何帮助。

谢谢

【问题讨论】:

  • Menu.js 长什么样子?
  • JavaScript 和 Java 是完全不同的语言。请不要使用 Java 标记标记 JS 问题。

标签: javascript reactjs jsx


【解决方案1】:

这可能是因为您的组件在获得 product.img 值之前正在渲染。试试下面的代码。

if(product && product.img){
const { fixed } = product.img;
}

return (
    <>
{fixed 
  &&(
    <ProductWrapper>
      <Img fixed={fixed} className="img" />
      <div className="text">
        <div className="product-content">
          <h3 className="name">{name}</h3>
          <h3 className="price">${price}</h3>
        </div>
        <p className="info">{ingredients}</p>
      </div>
    </ProductWrapper>
  )
   </>
  )

【讨论】:

  • 我认为你不能引用fixed,因为你有条件地声明fixed
猜你喜欢
  • 2020-01-29
  • 2019-09-24
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多