在遵循了一个教程并使用了代码之后,我的天气应用程序开始工作了。如果我没有输入任何值并按下按钮,还会收到一条不错的错误消息,但是如果我输入“错误”值(城市不在API数据库中),则应用崩溃。我是否有可能拥有实时输入搜索字段之类的东西?例如,如果我开始输入“ MA…”,则只会显示带有前两个字母的城市,我可以单击其中任何一个吗?另外,另一个问题是,有些城市的名称相同,所以我真的需要该实时搜索选项。如果这太困难了,如果城市不在API的数据库中,我该如何阻止我的应用崩溃?
import React from 'react';
import Titles from "./components/Titles";
import Form from "./components/Form";
import Weather from "./components/Weather";
const API_KEY = "7b31fc51d965595f7ad494ff430bf91f";
class App extends React.Component {
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
pressure: undefined,
description: undefined,
error: undefined
}
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
const api_call = await
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${API_KEY}&units=metric`);
const data = await api_call.json();
if (city) {
this.setState({
temperature: data.main.temp,
city: data.name,
country: data.sys.country,
humidity: data.main.humidity,
pressure: data.main.pressure,
description: data.weather[0].description,
error: ""
});
} else {
this.setState({
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
pressure: undefined,
description: undefined,
error: "Please enter values..."
});
}
}
render() {
return (
<div>
<div className="wrapper">
<div className="main">
<div className="container">
<div className="row">
<div className="col col-xs-6 col-sm-6 col-md-6 col-lg-6 col-xl-6 title-container">
<Titles />
</div>
<div className="col col-xs-6 col-sm-6 col-md-6 col-lg-6 col-xl-6 form-container">
<Form getWeather={this.getWeather}/>
<Weather
temperature={this.state.temperature}
city={this.state.city}
country={this.state.country}
humidity={this.state.humidity}
pressure={this.state.pressure}
description={this.state.description}
error={this.state.error}
/>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
};
export default App;