我一直试图理解为什么在尝试绘制TypeError: Cannot read property 'map' of undefined
时会得到this.state.forecastData
。.我一直在摆弄并尝试其他事情,但我没有将其绘制出来。
有人可以指出我正确的方向并描述我做错了什么吗? (我正处于ReactJS的学习阶段)
我可以console.log(res)
然后在控制台中得到这个:
这是我的组件:
import React, { Component } from 'react';
var queryString = require('query-string');
var api = require('../utils/api');
class Forecast extends Component {
constructor(props) {
super(props);
this.state = {
forecastData: [],
loading: false
}
this.makeRequest = this.makeRequest.bind(this);
}
componentDidMount () {
this.city = queryString.parse(this.props.location.search).city;
this.makeRequest(this.city);
}
componentWillReceiveProps(nextProps) {
this.city = queryString.parse(nextProps.location.search).city;
this.makeRequest(this.city);
}
makeRequest (city) {
this.setState(function () {
return {
loading: true,
}
})
api.getCurrentWeather(city)
.then(function (res) {
console.log(res)
this.setState(function () {
return {
forecastData: res,
loading: false,
}
})
}.bind(this))
}
render() {
return this.state.loading === true
? <h1 className='forecast-header'> Loading </h1>
: <div>
<h1 className='forecast-header'>{this.city}</h1>
<div className='forecast-container'>
{this.state.forecastData.list.map(function (listItem) {
return <div>Test</div>
}, this)}
</div>
</div>
}
}
export default Forecast;
答案 0 :(得分:0)
{this.state.forecastData.list.map(function (listItem) {
return <div>Test</div>
}, this)}
应该是
{this.state.forecastData.map(function (listItem) {
return <div>Test</div>
}, this)}
由于您正在访问list
中的forecastData
,但是forecastData
已经是您可以映射的数组。