javascript - 显示不存在的城市的错误消息?

标签 javascript reactjs

当用户输入不存在的城市时,我需要显示错误的帮助。该应用程序当前崩溃,但它应该显示“请输入现有城市”。有人可以帮忙吗?

Нужно помочь с написанием ошибки。 Например, когда пользователи вводят несуществующий город, приложение не крашится, но оно должно показывать: пожал уйста,напишите существующий город。 Может кто-нибудь помочь с этим?

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/

相关文章:

javascript - 使用数组中的值填充表行

css - 如何使我的图像内联到我的组件内容的左侧?

javascript - typescript 泛型定义依赖

javascript - 拆分 vendor bundle

javascript - 在 Javascript/jQuery 中生成表格

javascript - yarn 升级以修复 yarn 审计错误

javascript - 如何使用 Firebug 查找 CSS 属性并使用 Javascript 更改它

reactjs - 我如何使用 react 光滑 slider 来实现网格轮播布局

reactjs - PrimeReact 数据表 - 如何在单元格上显示工具提示或标题?

javascript - Three.js Loader.load() 中的错误处理