简体   繁体   English

如果输入的用户名不存在于github上,我会收到一条错误消息

[英]I want an error message if the entered username is not present on github

It's a react app and I am fetching the user data through github api. 这是一个React应用,我正在通过github api获取用户数据。 I want an error message if the entered username is not present on github. 如果输入的用户名不存在于github上,我会收到一条错误消息。 The rest of the search is working fine but I am unable to display the error. 其余的搜索工作正常,但我无法显示该错误。 I have tried showing the error when the response status is 404 but it hasn't work. 我尝试在响应状态为404但却无法正常工作时显示错误。 Could somebody please help me with this? 有人可以帮我吗?

 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; 

Try this. 尝试这个。 I corrected your code. 我更正了您的代码。 I have explained in code as comments for your understanding 我已经在代码中解释为注释,供您理解

PFB corrected code 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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想提醒错误信息 - I want to alert an error message 我想在 div 元素上附加错误消息 - I want to append error message on div element 我想在 ReactJS 表单中显示错误消息 - I want to show Error message in ReactJS Form 我在 instagram-private-api 中收到错误消息“您输入的用户名似乎不属于某个帐户” - I'm getting the error "The username you entered doesn't appear to belong to an account" in instagram-private-api 仅当使用jquery未正确输入用户名或密码时,如何显示错误消息? - How can I get my error messages to display only if username or password is not entered correctly using jquery? 如果用户不存在于数据库中,我想打印错误文本 - I want to print error-text if user will not be present in the database 如何修复此错误以及如何正确编写 github 用户名? 是有美元符号还是没有? - How can I fix this error and how do I write my github username correctly? is it with a dollar sign or without? 我希望“您已进入 X 级别”消息仅显示一次。 请阅读完整的问题以更好地理解它 - I want the "YOU ENTERED LEVEL X" message to be displayed only once. Please read the full question to understand it better PHP死于抛出与我想要的错误消息不同的错误消息 - PHP die throwing different error message than I want it to 我想在jQuery的多步骤表单中显示错误消息 - i want to display error message in my multiple step form in jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM