gpt4 book ai didi

javascript - React .map() 不是函数错误

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:15 26 4
gpt4 key购买 nike

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

export default class App extends Component {

constructor() {
super();
this.state = {
weather: []
};
}
componentDidMount (){

this.search();
}
search = () => {

axios.get("http://api.openweathermap.org/data/2.5/weather?q=Houston&APPID=f2327cca8f3d665f4c9f73b615b294ed")
.then(res => {

this.setState({weather: res.data});

}).catch(error => {
console.log('Error from fetching data', error);
})
}

render() {
console.log(this.state.weather);
const weathermap = this.state.weather.map( (maps) =>{
{maps.wind.speed}
});

return (
<div className="container">
<div className="row">
<div className="col-md-4 col-md-offset-4">
<div className="weather">
<div className="current">
<div className="info">
<div>&nbsp;</div>
<div className="city">
<small>
<small>CITY:</small>
</small>
{this.state.weather.name}</div>
<div className="temp">67&deg;
<small>F</small>
</div>
<div className="wind">
<small>
<small>WIND:{weathermap}</small>
</small>

</div>
<div>&nbsp;</div>
</div>
<div className="icon">
<span className="wi-day-sunny"></span>
</div>
</div>
<div className="future">
<div className="day">
<h3>Mon</h3>
<p>
<span className="wi-day-cloudy"></span>
</p>
</div>
<div className="day">
<h3>Tue</h3>
<p>
<span className="wi-showers"></span>
</p>
</div>
<div className="day">
<h3>Wed</h3>
<p>
<span className="wi-rain"></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>

);
}
}

我收到“this.state.weather.map 不是函数”错误。我正在从 weather api 获取数据。我从 api 得到的名字显示正常。 api 调用它自己是可以的也是成功的。这里的 api 在控制台中的样子 enter image description here

这是代码

最佳答案

您通过说 this.state = { weather: []}; 来实例化应用程序。但是,当您说 this.setState({weather: res.data}) 时,您正在将 this.state.weather 覆盖为 JavaScript 对象 而不是 array,因此 .map 不再可用。

您可以通过简单地 const weathermap = this.state.weather.wind.speed

实现您想要做的事情

关于javascript - React .map() 不是函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42989716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com