我正在从API获取数据,但在将它们显示到屏幕上时遇到了问题。当用户在表单中键入内容并单击“提交”按钮时,我想获取数据。
我有一个错误:
类型错误:无法读取空的“main”属性
我不明白为什么这些数据不显示在屏幕上。如果没有一个被展示出来,对我来说会更有意义。但是如果我评论这一行,childcomponent中的props.data.city将正确显示。我的代码:
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>
);