我正在调用 api 并获得响应,然后将响应数据设置为状态。问题是在 setState 之后状态仍未定义,并且不会使用 api 数据更新 Weather 组件
class App extends React.Component {
state = {
temperature: undefined,
icon: undefined,
time: undefined,
timezone: undefined,
description: "123"
};
getWeather = async e => {
e.preventDefault();
const location = e.target.elements.city.value;
const api_call = await fetch(`${GEO_API_URL}${location}`);
const lngLat = await api_call.json();
console.log(lngLat);
const api_call2 = await fetch(
`${API_URL}${lngLat.latitude},${lngLat.longitude}/?lang=sl&units=si`
);
const forecast = await api_call2.json();
console.log(forecast);
this.setState = {
temperature: forecast.currently.temperature,
icon: forecast.currently.icon,
time: forecast.currently.time,
timezone: forecast.timezone,
description: forecast.currently.summary
};
console.log(this.state.temperature);
};
render() {
return (
<div>
<Form getWeather={this.getWeather} />
<Weather
temperature={this.state.temperature}
icon={this.state.icon}
time={this.state.time}
timezone={this.state.timezone}
description={this.state.description}
/>
</div>
);
}
}
export default App;
慕工程0101907
偶然的你
相关分类