Я получаю данные из API, и у меня проблема с отображением их на экране.Я хочу получить данные, когда пользователь вводит что-то в форму и нажимает кнопку «Отправить».У меня ошибка:
Ошибка типа: невозможно прочитать свойство 'main' со значением null
Я не понимаю, почему эти данные не отображаются на экране.Если бы ни один из них не отображался, это было бы для меня больше смысла.Но если я прокомментирую эту строку, props.data.city из ChildComponent отобразится правильно.Мой код:
class ExampleComponent extends Component {
state = {
city: null
}
getData = async e => {
e.preventDefault();
const city = e.target.elements.city.value;
const getData = await fetch(`${url}${city}&appid=${key}`);
const data = await getData.json();
this.setState({
city: data
});
console.log(this.state.city); // return correct value, not null
console.log(this.state.city.main.temp_min); // return correct value, not null
}
render() {
return (
<>
<FormComponent onSubmit={this.getData} />
<ChildComponent data={this.state.city} />
</>
);
}
}
const FormComponent = props => (
<form onSubmit={props.getData}>
<input type="text" name="city" />
<button type="submit">do it</button>
</form>
);
const ChildComponent = props => (
<div>
<h3>{props.data.city}</h3>
<h4>{props.data.main.temp_min}</h4>
</div>
);