这是我到目前为止所做的,但在尝试从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} °C | {this.state.temperature} °F</span>
</div>
)
}
}
export default Weather
答案 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 } }