javascript - 在 Reactjs 中出现错误。它说未处理的拒绝(TypeError)。但我已经告诉它如果用户在输入中输入无效名称该怎么办

标签 javascript reactjs react-native web-development-server

只是想知道我是否可以得到 Unhandled Rejection (TypeError)。我已经放置了一个 if else 语句,告诉它呈现一个或另一个。结果,或提示输入有效国家/地区的消息。我已经在网上看了一段时间。请告诉我。谢谢。这是我的代码和错误图片。

import React, { Component } from 'react';
import './App.css';
import NavBar from "./navbar";
import axios from "axios";
import Accordion from './accordion';
import Accordions from './accordion';
import ErrorBoundary from "./Carousel";


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      flag: undefined,
      name: undefined,
      nativeName:undefined,
      callingCodes: undefined,
      capital: undefined, 
      currencies:undefined,
      languages: undefined,
      region:undefined,
      population:undefined,
      alpha3Code:undefined,
      isSearched: false,
      subregion: undefined,
      error: ""
    }
  }


  getCity = async(e) => {
    e.preventDefault();
    const city = e.target.elements.cityname.value;
    const api_call = await fetch(`https://restcountries.eu/rest/v2/name/${city}?fullText=true`);
    const data = await api_call.json();
    console.log(data);
    this.setState({
      flag: data[0].flag,
      name: data[0].name,
      nativeName: data[0].nativeName,
      alpha3Code: data[0].alpha3Code,
      callingCodes: data[0].callingCodes,
      capital: data[0].capital,
      currencies: data[0].currencies[0].name,
      languages: data[0].languages[0].name,
      region: data[0].region,
      population: data[0].population,
      subregion:data[0].subregion
    });
}

toggleSearch = () => {
  this.setState({
    isSearched: true
  })
}



  render() {
    let search;
    if(this.state.isSearched) {
      search = 
      <div className="content-1">
      <div className="marginbottom">
        <img className="flags" src={this.state.flag}/>
          <h2><span className="bold">Name:</span> {this.state.name}</h2>
          <div><span className="bold">Native Name:</span> {this.state.nativeName}</div>
          <div><span className="bold">Abbreviation:</span> {this.state.alpha3Code}</div>
          <div><span className="bold">Calling Code:</span> {this.state.callingCodes}</div>
          <div><span className="bold">Capital: </span>{this.state.capital}</div>
          <div><span className="bold">Currencies:</span> {this.state.currencies}</div>
          <div><span className="bold">Language:</span> {this.state.languages}</div>
          <div><span className="bold">Region: </span>{this.state.region}</div>
          <div><span className="bold">Population:</span> {this.state.population}</div>
        </div>
        <Accordions name={this.state.name} population={this.state.population} subregion={this.state.subregion}/>
      </div>
    } else {
      search=<p>Enter a valid country name</p>;
    }

    return (
      <div className="App">
        <header className="App-header">
          <h1>Globe Search</h1>
          <h5>Search For Cities Around the Globe</h5>
        </header>
      <div class="content">
      <NavBar/>
      <form
         onSubmit={this.getCity}   >
            <input
               placeholder="Enter Country"
               type="text"
               name="cityname"/>
            <button onClick={this.toggleSearch} className="btn btn-success m-2">Search</button>
          </form>
          <div>
        <div>{search}</div>
        </div>  
      </div>
      </div>
    );
  }
}

export default App;

最佳答案

当您提交空值或无效位置时,您将收到错误消息,因为您将尝试获取未知网址。所以你可以检查 city 值是否为空,也可以检查来自 api 的响应并相应地更新状态

 getCity = async(e) => {
    e.preventDefault();
    const city = e.target.elements.cityname.value;
    // check if input field is empty or not
    if(city) {
      const api_call = await fetch(`https://restcountries.eu/rest/v2/name/${city}?fullText=true`);
      const data = await api_call.json();
      console.log(data);
      // check if value entered in input is valid 
      // so check api returns a valid response or not
      if(data && !data.status) {
        this.setState({
        isSearched: true,
        flag: data[0].flag,
        name: data[0].name,
        nativeName: data[0].nativeName,
        alpha3Code: data[0].alpha3Code,
        callingCodes: data[0].callingCodes,
        capital: data[0].capital,
        currencies: data[0].currencies[0].name,
        languages: data[0].languages[0].name,
        region: data[0].region,
        population: data[0].population,
        subregion:data[0].subregion
       });
      } else {
        this.setState({
          isSearched:false
        })
      }   
    } else {
      this.setState({
        isSearched:false
      })
    }    
  }

同时将按钮更改为 type="submit"

<button type="submit" className="btn btn-success m-2">Search</button>

不需要toggleSearch方法

一切都会好起来的

关于javascript - 在 Reactjs 中出现错误。它说未处理的拒绝(TypeError)。但我已经告诉它如果用户在输入中输入无效名称该怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55285096/

相关文章:

javascript - 如何从循环中使用下一张图片加载多张图片?

reactjs - 如何修复设备: (3:2294) null is not an object (evaluating 'f.getRandomBase64' ) uuid react-native

javascript - 为什么我得到 "undefined is not an object (evaluating PropTypes.shape)"?

reactjs - React-Native 按钮居中对齐

javascript - Facebook react : Invariant Violation and elements than didn't mount automatically

javascript - 使用 Javascript 获取默认媒体播放器?

javascript - JSON 的频率分布

c# - 将 ViewModel 数据返回到 Javascript 函数 MVC 4?

javascript - 为什么在 React 和纯 CSS 中呈现的相同代码会提供不同的结果 :

javascript - 发布的 github 页面上出现 "Failed to create temp file 18"错误