我正在调用天气api,它以数据作为响应。我能够从对象中获取一些数据,但是当我尝试获取某些数据时,它在React中给了我对象错误。
class Weather extends React.Component{
constructor(props){
super(props);
this.state = {
weatherData: []
}
}
componentDidMount() {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=Brampton,ca&units=metric&mode=json`)
.then(res => {
const weatherData = res.data;
this.setState({ weatherData });
})
}
render(){
return(
<div>
WetherData<br/>
{JSON.stringify(this.state.weatherData)}
<ul>
<li>{this.state.weatherData.name}</li>
<li>{JSON.stringify(this.state.weatherData.weather)}</li>
</ul>
</div>
)
}
}
ReactDOM.render(<Weather />, document.getElementById('app'))
原始数据
"coord":{"lon":-79.76,"lat":43.69},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":10.06,"pressure":1017,"humidity":81,"temp_min":7.78,"temp_max":12.22},"visibility":24140,"wind":{"speed":4.1,"deg":10},"clouds":{"all":90},"dt":1556908224,"sys":{"type":1,"id":1002,"message":0.0067,"country":"CA","sunrise":1556878127,"sunset":1556929377},"id":5907364,"name":"Brampton","cod":200}
{JSON.stringify(this.state.weatherData.weather)}我在这里获取数据。
但是当我尝试
{JSON.stringify(this.state.weatherData.weather.main)},它给我对象错误。
或 如果我尝试
{JSON.stringify(this.state.weatherData.coord)}有效
但是
{JSON.stringify(this.state.weatherData.coord.lon)}给我一个对象错误