【发布时间】:2019-07-30 20:03:42
【问题描述】:
我是 React 世界的新手。我正在创建天气应用程序,并且正在使用 openweathermap api 来获取数据(使用了暗夜 api 并且遇到了同样的问题)。 问题是我得到一个获取数据并将其保存到状态。我可以通过 JSX 和 console.log 打印该状态的全部内容,但无法访问内部的特定数据(通过 console.log 和 JSX)。 问题说: TypeError: Cannot read property 'city' of undefined
这是我的代码:
import React from 'react';
import TemperaturesList from './TemperaturesList';
import axios from 'axios';
class WeatherData extends React.Component {
state = { weatherData: {}, error: null };
componentDidMount(){
axios.get('https://samples.openweathermap.org/data/2.5/forecast?lat=${this.props.lat}&lon=${this.props.long}&appid=MYAPPID')
.then(result => this.setState({
weatherData: result
}))
.catch(error => this.setState({
error: error
}))
}
render(){
return(
<div>
{JSON.stringify(this.state.weatherData)} // this works
<h3>Current weather:</h3>
{JSON.stringify(this.state.weatherData.data.city)} // this does not work
</div>
);
};
};
export default WeatherData;
这是我从状态中获取和保存的结果:
【问题讨论】:
标签: javascript reactjs api typeerror