ReactJS fetch - 无法读取属性' map'未定义的

时间:2018-03-25 18:27:48

标签: javascript reactjs fetch

如何从https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text=%22auckland%22)&format=json&env=store://datatables.org/alltableswithkeys获取tempicon

这是我到目前为止所做的,但在尝试从Yahoo Weather获取数据时获得Unhandled Rejection (TypeError): Cannot read property 'map' of undefined。我已经查看了'map' of undefined的其他解决方案,但似乎没有一个能解决我的问题。

import React, { Component } from 'react';

class Weather extends React.Component {
    constructor() {
        super();
        this.state = {
            temperature: [],
        };
    }
    componentWillMount() {

        fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22auckland%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
            .then(results => {
                return results.json();
            }).then(data => {
                var temperature = data.results.map((temps) => {
                    return(
                        <span key={temps.results}>
                            {temps.condition.temp}
                        </span>
                    )
                })
                this.setState({temperature: temperature});
                console.log("state", this.state.temperature);
            })
    }

    render() {
        return ( 
            <div id="weather">
                <span>{this.state.temperature} &deg;C | {this.state.temperature} &deg;F</span>
            </div>
        )
    }    
}

export default Weather

2 个答案:

答案 0 :(得分:3)

data是一个具有如下结构的对象:

{
query:
  count: 1
  ...
  results: {
    channel: {
      astronomy: { }
      atmosphere: { }
      ...

因此,要访问results媒体资源,您必须访问data.query.results

const results = data.query.results

但是有两个问题:results是一个对象,而不是一个数组,因此你不能.map它,而且似乎没有condition键入它。

也许你正在寻找这样的东西:

fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22auckland%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys')
  .then(results => {
  return results.json();
}).then(data => {
  const temp = data.query.results.channel.item.condition.temp;
  console.log(temp);
});

答案 1 :(得分:2)

正如我从你提供的链接中看到的那样,响应的结构有点不同。

您希望它是:

{ results: any }

但实际上它是:

{ query: { results: any } }