为什么这个反应组件没有搜索github的api不呈现?

时间:2018-04-20 13:04:17

标签: javascript json reactjs components github-api

您好我正在通过从github的API中提取github用户信息来练习React。我有一切正确布局或看起来如此,但组件由于某种原因不会呈现。这是我的代码:

      class GitHubSearch extends React.Component {

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

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>
        <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">
                {this.state.username} <br/>
                {this.state.id}
            </p>
    </div>
    );
   }
}

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

HTML:

      <div id="container">

     </div>

jsfiddle的编辑只是说语法错误,但我知道没有任何问题,但是对于事物的另一双眼睛总是好的。如果有什么我在看的话,请告诉我

1 个答案:

答案 0 :(得分:1)

更新构造函数以修复语法错误:

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

修改

这里也有错误:

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