当用户输入不存在的城市时,我需要显示错误的帮助。该应用程序当前崩溃,但它应该显示“请输入现有城市”。有人可以帮忙吗?
Нужно помочь с написанием ошибки。 Например, когда пользователи вводят несуществующий город, приложение не крашится, но оно должно показывать: пожал уйста,напишите существующий город。 Может кто-нибудь помочь с этим?
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;
最佳答案
当前您的代码
if (city) {
仅检查 const city 是否有值。即使用户提供了一个不存在的城市,这始终是正确的。
这是检查城市是否存在的API。如果没有,它将返回:
{
"cod": "404",
"message": "city not found"
}
因此您需要使用 API 中的此信息。一种方法是说,好的,如果城市存在,API 返回“名称”字段;如果没有,则没有“名称”字段:
const data = await api.json();
if (data.name) {
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."
});
}
};
关于javascript - 显示不存在的城市的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107428/