简体   繁体   English

无法读取未定义的属性“地图”-ReactJs

[英]Cannot read property 'map' of undefined - ReactJs

So i've done an axios get request to a yelp api.所以我已经对 yelp api 进行了 axios get 请求。 I can get the data, as I am console.logging 20 results in an object array.我可以获得数据,因为我是 console.logging 20 结果在一个对象数组中。

However, when I try to map through my results, I get two errors in my console:但是,当我尝试映射结果时,控制台中出现两个错误:

app.js:53912 Uncaught TypeError: Cannot read property 'map' of undefined and Unhandled rejection TypeError: Cannot read property 'map' of undefined app.js:53912 未捕获的类型错误:无法读取未定义未处理的拒绝属性“地图”类型错误:无法读取未定义的属性“地图”

Not sure, what I'm doing wrong....不确定,我做错了什么......

Here is the code for the axios request... perhaps this isn't assigning data to me state properly:这是 axios 请求的代码......也许这没有正确地将数据分配给我的状态:

 getYelp = () => {
// const params = {lat: this.state.lat, lng: this.state.lng};
const params = {latitude: 34.019864, longitude: -118.490541 };
const urlProxy = 'https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search';
Promise.props({
  businesses: axios({
    url: urlProxy,
    params: params,
    json: true,
    method: 'GET',
    headers: {
      'Authorization': 'Bearer MY_API_KEY',
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Allow-Origin': 'http://localhost:8000'
    }
  })
    .then(res => console.log('YELP', res.data.businesses))
    // .then(res => res.data)
    .catch(err => console.log(err))
 })
  .then(data => {
    this.setState({
      businesses: data.businesses
    });
  });
 }

And here's the mapping code:这是映射代码:

    <section className="section">
      <div className="has-text-centered">
        <h1 className="has-text-centered cat-titles">YELP:</h1>
      </div>
      <ul className="columns is-multiline">
        {this.state.businesses.map((business, i) =>
          <li key={i} className="column is-one-third">
            <div className="container card">
              <div className="">
                <div className="card-image">
                  <figure className="box">


                    <p className="is-size-4 has-text-left has-text-black">{business.name}</p>
                    <p className="has-text-left">{business.name}</p>

                  </figure>
                </div>
              </div>
            </div>
          </li>)}
      </ul>
    </section>

I'm running the getYelp();我正在运行 getYelp(); function in componentDidMount. componentDidMount 中的函数。

And I have another axios request pulling through/mapping data fine on the page too.而且我还有另一个 axios 请求,也可以在页面上很好地提取/映射数据。 Just can't figure out what I've missed here...只是无法弄清楚我在这里错过了什么......

UPDATED!!!更新!!!

I'm including the full page code here:我在这里包含了完整的页面代码:

import React from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Promise from 'bluebird';
import '../../assets/scss/main.scss';

import GoogleMaps from '../../components/common/GoogleMaps';
import Footer from '../../components/common/Footer';
// import Darksky from '../../components/common/Darksky';


// const rp = require('request-promise');

class Hub extends React.Component {

state =  {
  places: null,
  articles: null,
  user: null,
  // latlng: null
  lat: null,
  lng: null,
  businesses: []
}

 setLocation = (lat, lng) => {
   console.log('location set...', lat, lng);
   this.setState({ lat: lat, lng: lng }, this.getPlaces);
 }

getYelp = () => {
// const params = {lat: this.state.lat, lng: this.state.lng};
const params = {latitude: 34.019864, longitude: -118.490541 };
const urlProxy = 'https://cors- 
   anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search';
   Promise.props({
     businesses: axios({
       url: urlProxy,
       params: params,
       json: true,
       method: 'GET',
       // withCredentials: true,
       headers: {
         'Authorization': 'Bearer MY_API_KEY',
         'Accept': 'application/json',
         'Content-Type': 'application/json',
         // 'Origin': 'http://localhost:8000',
         'Access-Control-Allow-Headers': '*',
         'Access-Control-Allow-Origin': 'http://localhost:8000'
       }
     })
    .then(res => console.log('YELP', res.data.businesses))
    // .then(res => res.data)
    .catch(err => console.log(err))
})
  .then(data => {
    this.setState({
      businesses: data.businesses
    });
  });
}

 componentDidMount() {
  this.getYelp();
 }

 render() {
 console.log('PLACES', this.state.places);

// if businesses is null/false and nothing has loaded, dont run the 
code below.
// if businesses is truthy, then run code below
if (!this.state.businesses) return false;
return (

  <main>
    <section className="hero hub-image section-top">
      <div className="hero-body no-padding">
        <div className="has-text-centered">
          <h1 className="hub-title">Your Travel Hub</h1>
        </div>
      </div>
    </section>
    {/* <Darksky /> */}

    <section className="section">
      <div className="columns">
        <div className="column">
          <GoogleMaps setLocation={this.setLocation} />
        </div>
      </div>
    </section>

    <section className="section">
      <div className="has-text-centered">
        <h1 className="has-text-centered cat-titles">YELP:</h1>
      </div>
      <ul className="columns is-multiline">
        {this.state.businesses.map((business, i) =>
          <li key={i} className="column is-one-third">
            <div className="container card">
              <div className="">
                <div className="card-image">
                  <figure className="box">


                    <p className="is-size-4 has-text-left has-text-black">{business.name}</p>
                    <p className="has-text-left">{business.name}</p>

                  </figure>
                </div>
              </div>
            </div>
          </li>)}
      </ul>
    </section>

    <Footer />
  </main>
   );
 }
}
export default Hub;

componentDidMount is called when component's jsx is executed. componentDidMount在组件的jsx执行时被调用。 Your jsx has a call of this.state.businesses , but it probably not defined, as it gets defined only after mount .您的jsx调用了this.state.businesses ,但它可能未定义,因为它仅在mount之后定义。

Although you didn't show your code for the constructor, the first issue that comes to my mind is that your businesses inside the state is not defined.尽管您没有显示构造函数的代码,但我想到的第一个问题是未定义state内的businesses

Please in your constructor put the following code:请在您的构造函数中输入以下代码:

constructor(props) {
    super(props);

    this.state = {
        businesses: [],
    }
}

This will solve your problem.这将解决您的问题。

Cause: you are trying to loop with a map of an undefined variable, you are not taking into account the time that your axios calls take to solve and save the values into the state (with time I mean the time of the request/response)原因:您正在尝试使用未定义变量的map进行循环,您没有考虑您的 axios 调用解决并将值保存到状态所需的时间(时间是指请求/响应的时间)

You should check this.state.business exists before doing a map.在绘制地图之前,您应该检查 this.state.business 是否存在。

const business = this.state.business ? this.state.business : [];

then do a map over business然后做一张生意地图

Live sample code实时示例代码

https://codesandbox.io/s/24r49nyp5p https://codesandbox.io/s/24r49nyp5p

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM