我需要用户输入不存在的城市时显示错误的帮助。该应用程序当前崩溃,但应显示“请输入现有城市”。 С有人对此有帮助吗?
Нужнопомочьснаписаниемошибки。 Например,когдаполязнесуществующийгород,приложениенекрашится,ноооноеное Можеткто-нибудьпомочьсэтим?
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;
api返回json数据
{
"cod": "404",
"message": "city not found"
}
当城市无效时。
所以您可以查看您返回的响应,如果您获得cod: 200
,则该城市为有效城市。如果得到cod: 404
,则应该执行错误消息处理。