【发布时间】:2022-01-07 08:47:38
【问题描述】:
我是反应 js 的新手。我通过创建一个简单的应用程序来学习它。我尝试使用 react 类组件创建一个简单的天气应用程序。一切正常,但存储在状态变量中的结果未在模板中打印。我可以在控制台中看到 API 响应,然后将结果存储在模板中未显示的“currWeatherRes”状态变量中(位置始终为空白)
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
cityName: "",
currWeatherRes: {}
}
}
handleSubmit = (event) => {
event.preventDefault();
alert(`The name you entered was:`+ this.state.cityName);
fetch(`https://api.openweathermap.org/data/2.5/weather?q=`+this.state.cityName+`&appid=f3ee66722740d00cc6f197cbcab3d534`, {
method: 'GET'
}).then((response) => {
console.log(response)
this.setState({
currWeatherRes: response
})
//return response.json();
});
}
handleChange = (event) => {
this.setState({cityName:event.target.value});
}
render() {
return (
<div className="weather-app">
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.cityName} onChange={this.handleChange} placeholder="Enter City"/>
<button type="submit" value="Submit">Submit</button>
</form>
{(typeof this.state.currWeatherRes.main != "undefined") ? (
<div className="weather-details">
<div className="weather-location">
<div className="location">Loctaion: {this.state.currWeatherRes.name}</div>
</div>
</div>
):('')}
</div>
);
}
}
export default App;
【问题讨论】:
标签: javascript reactjs class state