当用户输入一个不存在的城市时,我需要帮助来显示错误。该应用程序当前崩溃,但应显示“请输入现有城市”。任何人都可以帮忙吗?
需要帮助编写错误。例如,当用户输入一个不存在的城市时,应用程序不会崩溃,但它应该显示:请输入一个存在的城市。有人能帮忙吗?
import React, { Component } from "react";
import WeatherInput from "./WeatherInput";
const KEY = "455137f97981800c10482bbc6539fba2";
class Weather extends Component {
constructor(props) {
super(props);
this.state = {
city: "",
country: "",
temperature: "",
main: "",
description: "",
error: ""
};
}
getWeatherInfo = async event => {
event.preventDefault();
const city = event.target.elements.city.value;
const country = event.value;
const api = await fetch(
`http://api.openweathermap.org/data/2.5/weather?q=${city},${country},uk&APPID=${KEY}`
);
const data = await api.json();
if (city) {
this.setState({
city: data.name,
country: data.sys.country,
temperature: data.main.temp,
main: data.weather[0].main,
description: data.weather[0].description,
error: ""
});
} else {
this.setState({
city: "",
country: "",
temperature: "",
main: "",
description: "",
error: "Please enter the values."
});
}
};
render() {
const { city, country, temperature, main, description, error } = this.state;
return (
<WeatherInput
getWeatherInfo={this.getWeatherInfo}
city={city}
country={country}
temperature={temperature}
main={main}
description={description}
error={error}
/>
);
}
}
export default Weather;
慕斯王
相关分类