代码之家  ›  专栏  ›  技术社区  ›  Darren

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

  •  -1
  • Darren  · 技术社区  · 6 年前

    我怎样才能把这个拿到 temp icon 从…起 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 ?

    这就是我目前所拥有的,但是 Unhandled Rejection (TypeError): Cannot read property 'map' of undefined 尝试从Yahoo Weather获取数据时。我已经研究了其他解决方案 '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 回复  |  直到 6 年前
        1
  •  4
  •   CertainPerformance    6 年前

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

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

    所以要访问 results 属性,您必须访问 data.query.results :

    const results = data.query.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);
    });
        2
  •  3
  •   Daniel Stoyanoff    6 年前

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

    您希望它是:

    { results: any }
    

    但实际上是:

    { query: { results: any } }