简体   繁体   English

TypeError:无法读取未定义 React state 的属性“图像”

[英]TypeError: Cannot read property 'image' of undefined React state

I am pulling data from an internal API that returns an image that I am trying to display.我从内部 API 中提取数据,该数据返回我要显示的图像。 I have a page function that is set to display the information from that response.我有一个页面 function 设置为显示来自该响应的信息。 The response is as follows for a single bottlebottle响应如下

{
   "data":{
      "id":"cc134653-c463-4e79-8b9e-f52dfe02498e",
      "type":"bottle",
      "attributes":{
         "name":"Luc Belaire Rare Luxe",
         "price":"$29.99",
         "image":"https://cdn11.bigcommerce.com/s-7a906/images/stencil/1000x1000/products/10929/10518/Luc-Belaire-Rare-Luxe__73902.1555086630.jpg?c=2",
         "sku":"813497005010",
         "size":"750ML",
         "origination":"France",
         "varietal":"Sparkling Wine"
      }
   }
}

I am new to React so I could be mistaken here, but this function is intended to display a loader, just a simple fontawesome spinner, until the data is available.我是 React 新手,所以在这里我可能会误会,但是这个 function 旨在显示一个加载器,只是一个简单的字体微调器,直到数据可用。

Here is the function这是 function

import React, { useState, useEffect } from 'react';
import { Loader } from '../../components/Loader'
import { endpoints } from "../../utils/fetch";

export default function Bottle({ match }) {
  let [bottle, setBottle] = useState([])

  useEffect(() => {
    fetch(`${endpoints().bottle}/${match.params.sku}`, { method: "GET" })
    .then(response => response.json())
    .then(data => setBottle(data.data))
  }, [])

  return (
    !bottle ? <Loader /> :
    <div className="card">
      <div className="card-body">
        <div className="row">
          <div className="mb-4 mb-lg-0 col-lg-6">
            <div>
              <div className="position-relative h-sm-100 overflow-hidden">
                <img className="img-fluid fit-cover w-sm-100 h-sm-100 rounded cursor-pointer" 
                  src={bottle.attributes.image} 
                  alt={bottle.attributes.name} 
                  height={200}
                  width={125} />
              </div>
            </div>
          </div>
          <div className="d-flex justify-content-between flex-column col-lg-6">
            <div>
              <h5>Apple iMac Pro (27-inch with Retina 5K Display, 3.0GHz 10-core Intel Xeon W, 1TB SSD)</h5>
              <a className="fs--1 mb-2 d-block" href="#!">Computer &amp; Accessories</a>
              <h4 className="d-flex align-items-center"><span className="text-warning mr-2">$1199.50</span></h4>
              <p className="fs--1 mb-1"><span>Shipping Cost: </span><strong>$50</strong></p>
              <p className="fs--1">Stock: <strong className="text-success">Available</strong></p>
            </div>
            <div className="row">
              <div className="col-auto">
                <button type="button" className="border-300 mr-2  btn btn-outline-danger btn-sm">
                  <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="heart" className="svg-inline--fa fa-heart fa-w-16 mr-1" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
                    <path fill="currentColor" d="M462.3 62.6C407.5 15.9 326 24.3 275.7 76.2L256 96.5l-19.7-20.3C186.1 24.3 104.5 15.9 49.7 62.6c-62.8 53.6-66.1 149.8-9.9 207.9l193.5 199.8c12.5 12.9 32.8 12.9 45.3 0l193.5-199.8c56.3-58.1 53-154.3-9.8-207.9z" />
                  </svg>
                  282
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

I would expect, based on what I've written, that the loader would display until the bottle has is not null.根据我所写的内容,我希望装载机将显示直到bottle不是 null。 Instead, I get the following error.相反,我收到以下错误。

在此处输入图像描述

Am I misusing state here?我在这里滥用 state 吗? I've tried to use async and await here but was not successful in getting the data to display.我尝试在这里使用asyncawait ,但未能成功显示数据。 Just the same error.只是同样的错误。

Your default value for bottle is [] , in JavaScript, an empty array is still considered truthy, so this will result in your component following the else path before your data has finished loading.您的bottle默认值为[] ,在 JavaScript 中,空数组仍被认为是真实的,因此这将导致您的组件在数据加载完成之前遵循 else 路径。

Also, when you are rendering the component, you are not using the data as an array anyway.此外,当您渲染组件时,无论如何您都不会将数据用作数组。

Change your useState to this:将您的 useState 更改为:

let [bottle, setBottle] = useState();

This will provide a default value of undefined to bottle , which should mean your ternary will behave correctly.这将为bottle提供默认值undefined ,这意味着您的三元组将正常运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React - TypeError:无法读取未定义的属性“图像” - React - TypeError: Cannot read property 'image' of undefined TypeError:无法读取未定义反应的属性“图像” - TypeError: Cannot read property 'image' of undefined react TypeError:无法读取 React 中未定义的属性“多对象中的状态名称” - TypeError: Cannot read property 'state name in much object' of undefined in React 未捕获的类型错误:无法读取未定义的属性“状态”-React.js - Uncaught TypeError: Cannot read property 'state' of undefined - React.js 使用酶进行反应测试TypeError:无法读取未定义的属性“state” - React test with enzyme TypeError: Cannot read property 'state' of undefined 类型错误:无法读取未定义的属性“状态”。 更新反应 - TypeError: Cannot read property 'state' of undefined. Updated React 未捕获的TypeError:无法读取未定义的反应状态项的属性&#39;toUpperCase&#39; - Uncaught TypeError: Cannot read property 'toUpperCase' of undefined react state item 反应未处理的拒绝(TypeError):无法读取未定义的属性“状态” - React Unhandled Rejection (TypeError): Cannot read property 'state' of undefined 反应 State:未捕获的类型错误:无法读取未定义的属性“值” - React State: Uncaught TypeError: Cannot read property 'value' of undefined react:uncaught TypeError:无法读取未定义的属性“state” - react: uncaught TypeError: Cannot read property 'state' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM