简体   繁体   English

未处理的拒绝(TypeError):尝试在 ReactJS 上使用 Axios 加载 API 数据时,无法读取未定义的属性“0”

[英]Unhandled Rejection (TypeError): Cannot read property '0' of undefined happening while trying to load API data with Axios on ReactJS

Trying to load the Open BreweryDB API in a ReactJS application to display a list of breweries in a US city.尝试在 ReactJS 应用程序中加载 Open BreweryDB API 以显示美国城市的啤酒厂列表。 Loading the information using axios and the async componentDidMount() method results in the "Unhandled Rejection (TypeError): Cannot read property '0' of undefined" error at line 34 (in my code) which would be breweryData = breweryData.data.results[0];使用 axios 和异步 componentDidMount() 方法加载信息会导致第 34 行(在我的代码中)出现“未处理的拒绝(TypeError):无法读取未定义的属性 '0'”错误,这将是 breweryData = breweryData.data.results [0];

I'm pretty new to ReactJS and API implementation.我对 ReactJS 和 API 实现很陌生。 I tried removing the ...results[0];我尝试删除 ...result[0]; portion, but I still got the same error as above, with an issue on the same line.部分,但我仍然遇到与上述相同的错误,并且在同一行出现问题。 Not sure how to solve this issue.不知道如何解决这个问题。 I'm able to render a "Loading..." element on the card if I ignore the error.如果我忽略错误,我可以在卡上呈现“正在加载...”元素。 Below is the code I am using in my App.js folder下面是我在 App.js 文件夹中使用的代码


import API from './utils/API';
import Brewery from './component/Breweries';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      name: null,
      address: null,
      brewery_type: null
    };
  }

  render() {
    const { isLoading, name, address, brewery_type } = this.state;

    return (
      <Brewery isLoading={isLoading} name={name} address={address} brewery_type={brewery_type} />
    );
  }

  async componentDidMount() {
    let breweryData = await API.get('/', {
      params: {
        results: 1,
        inc: 'name,address,brewery_type'
      }
    });

    breweryData = breweryData.data.results[0];

    const name = `${breweryData.name}`;
    const address = `${breweryData.address}`;
    const brewery_type = `${breweryData.brewery_type}`;

    this.setState({
      ...this.state, ...{
        isLoading: false,
        name,
        address,
        brewery_type
      }
    });
  }
}

export default App;

It should display a list of results displaying the name of the brewery, the address, and the brewery type (micro, major, etc.)它应该显示一个结果列表,其中显示啤酒厂的名称、地址和啤酒厂类型(微型、主要等)。

Above issue was fixed, however, the API data is not displaying.以上问题已修复,但未显示 API 数据。 Here is the code in the breweries.js file这是 breweries.js 文件中的代码

import PropTypes from 'prop-types';

import "bootstrap/dist/css/bootstrap.min.css";
import "shards-ui/dist/css/shards.min.css";

import { Card } from 'shards-react';

class Brewery extends React.Component {
    render() {
        const { name, street, city, state, postal_code, isLoading } = this.props;

        const breweryDetails = (
            <div>
                <h4 className="mb-0">{name}</h4>
                <span className="text-muted">{street}</span>
                <span className="text-muted">{city}</span>
                <span className="text-muted">{state}</span>
                <span className="text-muted">{postal_code}</span>
            </div>
        );

        const loadingMessage = <span className="d-flex m-auto">Loading...</span>;

        return (
            <Card
                className="mx-auto mt-4 text-center p-5"
                style={{ maxWidth: "300px", minHeight: "250px" }}
            >
                {isLoading ? loadingMessage : breweryDetails}
            </Card>
        );
    }
}

Brewery.propTypes = {
    name: PropTypes.string,
    street: PropTypes.string,
    city: PropTypes.string,
    state: PropTypes.string,
    postal_code: PropTypes.string,
    isLoading: PropTypes.bool
};

export default Brewery;

Change改变

breweryData = breweryData.data.results[0];

to

breweryData = breweryData.data[0]

or even better甚至更好

let returnedBreweryData = breweryData.data ? breweryData.data[0] : {}

It's maybe because you are not getting the result from API for some reason.这可能是因为您出于某种原因没有从 API 获得结果。 When you are using async await, you would want to handle the error too.当您使用 async await 时,您也需要处理错误。 Add a try catch block to your code and you should be fine在您的代码中添加一个 try catch 块,您应该没问题

暂无
暂无

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

相关问题 Reactjs + Redux 未处理的拒绝(TypeError):无法读取未定义的属性“数据” - Reactjs + Redux Unhandled Rejection (TypeError): Cannot read property 'data' of undefined 未处理的拒绝(typeError):无法在 google chrome mobile 上使用 reactjs axios 读取未定义的属性 - Unhandled Rejection (typeError): Cannot read property of undefined using reactjs axios on google chrome mobile axios:未处理的拒绝(TypeError):无法读取未定义的属性“错误” - axios: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined ReactJS:未处理的拒绝(TypeError):无法读取未定义的属性“推送” - ReactJS: Unhandled Rejection (TypeError): Cannot read property 'push' of undefined ReactJS - 未处理的拒绝(TypeError):无法读取未定义的属性“id” - ReactJS - Unhandled Rejection (TypeError): Cannot read property 'id' of undefined React API错误(未处理的拒绝(TypeError):无法读取未定义的属性“ 0”) - React API Error (Unhandled Rejection (TypeError): Cannot read property '0' of undefined) 未处理的拒绝(TypeError):无法读取未定义的属性 - Unhandled Rejection (TypeError): Cannot read property of undefined React/Redux:未处理的拒绝(TypeError):无法读取未定义的属性“数据” - React/ Redux : Unhandled Rejection (TypeError): Cannot read property 'data' of undefined 反应 - Redux | 未处理的拒绝(类型错误):无法读取未定义的属性“数据” - React - Redux | Unhandled Rejection (TypeError): Cannot read property 'data' of undefined React-未处理的拒绝(TypeError):无法读取未定义的属性“数据” - React- Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM