我正在调用api并获取响应,然后将响应数据设置为state。问题是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;
答案 0 :(得分:4)
尝试使用
this.setState({
temperature: forecast.currently.temperature,
icon: forecast.currently.icon,
time: forecast.currently.time,
timezone: forecast.timezone,
description: forecast.currently.summary,
});
代替
this.setState = ({
temperature: forecast.currently.temperature,
icon: forecast.currently.icon,
time: forecast.currently.time,
timezone: forecast.timezone,
description: forecast.currently.summary,
});
答案 1 :(得分:0)
为setState方法使用正确的格式。
this.setState({field: 'new value'});
现在像这样更改代码setState。
this.setState({
temperature: forecast.currently.temperature,
icon: forecast.currently.icon,
time: forecast.currently.time,
timezone: forecast.timezone,
description: forecast.currently.summary,
});
答案 2 :(得分:0)
此外,对于以前的评论,我建议您刷新官方文档https://reactjs.org/docs/react-component.html#setstate
中的 setState 理解