首页 > 解决方案 > React Fetch无法读取未定义的属性“地图”

问题描述

我正在进入Cannot read property 'map' of undefined我的 React 应用程序 - 虽然这通常意味着我正在搜索不正确的数据类型(例如,对象与数组),但我无法 console.log 我的 API URL,这让我想到了一些事情否则是错误的。

这是我的代码,所有内容都存在于我的 App.js 文件中,因此调用其他组件或任何东西都不是问题:

import React, { Component } from 'react';
import './App.css';

const APIURL = `https://api.openbrewerydb.org/breweries?`;
const citySearch = `by_state=new_york`;

class App extends Component {
  constructor() {
    super()

    this.state = {
      error: null,
      isLoaded: false,
      breweries: []
    };
  }

  componentDidMount() {
    fetch(APIURL + citySearch)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            breweries: result.breweries
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, breweries } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
    return (
          <ul>
            {breweries.map(brewery => (
              <li key={brewery.id}>
              {brewery.name} {brewery.city}
              </li>
            ))}
          </ul>
     );
    }
  }
}

export default App;

这是我要获取的数据 - 如果我将 APIURL 复制并粘贴到浏览器中,我会得到数据 - 所以我不确定undefined来自哪里:

[{"id":4581,"name":"Adirondack Toboggan Company Microbrewery","brewery_type":"micro","street":"202A W Main St","city":"Gouverneur","state":"New York","postal_code":"13642-1334","country":"United States","longitude":"-75.4748923846074","latitude":"44.3323731052224","phone":"3157716313","website_url":"http://www.adktoboggan.net","updated_at":"2018-08-24T15:37:58.899Z","tag_list":[]}, (AND SO ON)...

因为我刚刚启动了这个应用程序,所以我只是想确保我的 fetch 请求有效,以便我可以构建组件。

我是undefined因为我搜索数据的方式(这似乎是像我这样的其他问题的解决方案)还是发生了其他事情,甚至阻止我记录我的APIURLconst?

标签: reactjsfetch

解决方案


推荐阅读