如何使用 github api 在 React 中显示 github 用户信息?

How do I get the github user info to show up using github api in react?

我开始制作一个 React 应用程序,它可以通过用户名搜索 github 用户,其中包含一个显示用户名、个人资料头像、关注者数量、用户正在关注的人以及一个组件显示用户回购协议。到目前为止我有以下代码:

     class GitHubSearch extends React.Component {

         constructor(props){ 
           super(props); 
            this.state = { 
            username: '' 
          };
        }

getUser(username) {
    return fetch('https://api.github.com/users/${login}')
    .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>
        <p>{this.state.username} 
  <br/> 
    {this.state.id} 
  <br/> 
  </p>
        <img src={this.state.avatar_url}/>
    </div>
 }

return (
    <div className="GitHubSearch">
      <header className="Search-header">
        <h1>Github User Search </h1>
      </header>
    <form onSubmit={e => this.handleSubmit(e)}>
      <input ref='username' type='text' placeholder='username' />
    </form>
            <p className="Search-intro">
                {user}
            </p>
    </div>
    );
   }
 }

 ReactDOM.render(<GitHubSearch/>, document.getElementById('container'));

这是html:

        <div id="container">

        </div>

到目前为止搜索组件呈现,但是当我输入用户名时,我在控制台中收到此错误:GET https://api.github.com/users/$%7Blogin%7D 404 (Not Found)

我错过了什么?

您应该用反引号替换 fetch 函数中的引号,因为它们允许内联变量。正常引号没有。

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

您需要使用反引号来包裹您的 url (template literals):

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

另外,您正在使用 login 但它没有在任何地方定义。您要使用 username 吗?