gpt4 book ai didi

javascript - react 状态不重新渲染

转载 作者:行者123 更新时间:2023-11-28 14:15:42 25 4
gpt4 key购买 nike

我正在调用 api 并获取响应,然后将响应数据设置为状态。问题是 setState 之后状态仍然未定义,并且不使用 api 数据更新天气组件

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;

最佳答案

尝试使用

 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,
});

关于javascript - react 状态不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57572477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com