当用户输入不存在的城市时,我该怎么写错误?

问题描述 投票:0回答:1

需要有关书写错误的帮助。例如,当用户输入不存在的城市时,应用程序会崩溃,但应显示:请输入存在的城市。 С有人对此有帮助吗?

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

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;
javascript reactjs
1个回答
0
投票

api返回json数据

{
    "cod": "404",
    "message": "city not found"
}

当城市无效时。

所以您可以查看您返回的响应,如果您获得cod: 200,则该城市为有效城市。如果得到cod: 404,则应该执行错误消息处理。

© www.soinside.com 2019 - 2024. All rights reserved.