I'm making a weather app in React and I'm having problems accessing an array inside an object in state. Here is my code:
import React from 'react';
export default class CurrentWeather extends React.Component {
constructor(props) {
super(props);
this.state = {
weatherData: {},
};
}
componentDidMount() {
fetch("https://api.openweathermap.org/data/2.5/weather?q=City&appid=ID&units=metric")
.then(res => res.json())
.then(
(weatherData) => {
return this.setState({
weatherData: weatherData,
});
},
)
}
render() {
const getWeather = this.state.weatherData;
return (
<div>
<p>{ JSON.stringify(getWeather.weather) }</p>
{ /* [{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}] */}
<p>{ JSON.stringify(getWeather.weather[0]) }</p>
{ /* TypeError: getWeather.weather is undefined */}
</div>
);
}
}
I've commented with what happens, and I cannot figure out why this is happening. Below is what this.state.weatherData.weather contains:
"weather": [
{
"id": 600,
"main": "Snow",
"description": "light snow",
"icon": "13n"
}
]
question from:
https://stackoverflow.com/questions/65870013/react-typeerror-this-state-object-array0-is-undefined 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…