【发布时间】:2021-09-29 04:17:10
【问题描述】:
我遇到了错误TypeError: Cannot read properties of undefined (reading 'map')
此代码应返回卡片标题中的城市名称,该卡片标题在我的其他文件中定义,但会引发错误。
代码:
import React, {Component} from 'react';
import Body from './Body';
class Weather extends Component {
constructor(props) {
super(props);
this.state = {
weather: [],
};
}
async componentDidMount() {
const url = `http://api.weatherapi.com/v1/current.json?key=${this.props.api}&q=Jaipur&aqi=no`;
let data = await fetch(url);
let parsedData = await data.json();
this.setState({
weather: parsedData.weather,
});
}
render() {
return (
<div className="container">
<div className="row">
{this.state.weather.map((element) => {
return (
<div className="col-md-4">
<Body city={element.location.name} />
</div>
);
})}
</div>
</div>
);
}
}
export default Weather;
【问题讨论】:
-
您将
this.state.weather更新为parsedData.weather的值是多少?是数组吗? -
是的,这将存储我从 api 获取的所有天气详细信息的数组
-
请告诉我们
parsedData的值。据我所知,this.state.weather是在初始渲染上定义的数组,因此在您获取数据并更新状态后,this.state.weather不再定义。这就是您无法读取.map或.length并引发错误的原因。如果我有你的this.props.api值,我会自己复制它,看看响应值是什么。
标签: javascript reactjs