首页 > 解决方案 > 如果输入的用户名在 github 上不存在,我想要一条错误消息

问题描述

这是一个反应应用程序,我正在通过 github api 获取用户数据。如果输入的用户名在 github 上不存在,我想要一条错误消息。其余的搜索工作正常,但我无法显示错误。我尝试在响应状态为 404 时显示错误,但它不起作用。有人可以帮我解决这个问题吗?

import React, { Component } from 'react';
import './App.css';

// App component

class App extends Component {

  constructor(){
    super();
    this.state = {
      username: '',
      id: '',
      url: '',
      avatar_url: ''
    }
  }

  getUser(username){
    return fetch(`https://api.github.com/users/${username}`)
    .then(response => response.json())
    .then(response => {
      return response;
    })
  }

  async handleSubmit(e){
    e.preventDefault();
    let user = await this.getUser(this.refs.username.value);
    this.setState({
      username: user.login,
      id: user.id,
      url: user.url,
      avatar_url: user.avatar_url
    });
  }


  render() {
    let user;
    if(this.state.username){
      user =
      <div>
        <img alt="user-dp" src={this.state.avatar_url} width={"220px"} />
        <p><strong>Username: </strong>{this.state.username}</p>
        <p><strong>User id: </strong>{this.state.id}</p>
        <p><strong>Profile URL: </strong>
          <a href={"https://github.com/" + this.state.username}>{"https://github.com/" + this.state.username}</a>
        </p>
      </div>
    }
    return (
      <div className="app">
        <header className={"app-header"}>
          <h1>Github Finder</h1>
        </header>
        <form onSubmit={e => this.handleSubmit(e)}>
          <label className={"label-finder"}>Search github user: </label>
          <input className={"input-finder"} ref='username' type="text" placeholder='Enter Username' />
        </form>
        <div className={"user-data"}>
          {user}
        </div>
      </div>
    );
  }
}

export default App;

标签: javascriptreactjsapigithubecmascript-6

解决方案


尝试这个。我更正了你的代码。我已经在代码中解释为注释以供您理解

PFB 校正码

import React, { Component } from 'react';
import './App.css';

// App component

class App extends Component {

  constructor(){
    super();
    this.state = {
      username: '',
      id: '',
      url: '',
      avatar_url: '',
      user: ''
    }
  }

  getUser(username){
    return fetch(`https://api.github.com/users/${username}`)
    .then(response => response.json())
    .then(response => {
      return response;
    })
  }

  async handleSubmit(e){
    e.preventDefault();
    const user = await this.getUser(this.refs.username.value);
    //You can use user.ok to check whether the response is ok if yes set the user details otherwise user is not found so set the values to default one
    // I have taken additional variable to show error message when user is not found. If user found I will set user to "" empty string other wise I am setting user not found value to user.
    if(user.ok){
      this.setState({
        username: user.login,
        id: user.id,
        url: user.url,
        avatar_url: user.avatar_url,
        user: ''
      });
    }else{
      this.setState({
        username: '',
        id: '',
        url: '',
        avatar_url: '',
        user: 'not found'
      });
    }

  }


  render() {
    const { user, username,avatar_url, id } = this.state;
    // The above line reduces repeating this.state.xxx in render method
    return (
      <div className="app">
        <header className="app-header">
          <h1>Github Finder</h1>
        </header>
        <form onSubmit={e => this.handleSubmit(e)}>
          <label className="label-finder">Search github user: </label>
          <input className="input-finder" ref='username' type="text" placeholder='Enter Username' />
        </form>
        <div className="user-data">
          {/* You can directly check if user == "not found" then show error message using && operator*/}
          {user == 'not found' && (
            <div>
              <img alt="user-dp" src={avatar_url} width=220 />
              <p><strong>Username: </strong>{username}</p>
              <p><strong>User id: </strong>{id}</p>
              <p><strong>Profile URL: </strong>
                <a href={"https://github.com/" + username}>{"https://github.com/" + username}</a>
              </p>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default App;

推荐阅读