繁体   English   中英

我无法在React App中显示来自GitHub API的用户数据吗?

[英]I can't display user data from GitHub's API in a React App?

我知道我的代码中有错误,但是作为React新手,我无法弄清楚它们。 我的目标是从api获取用户,并在按下按钮后在屏幕上呈现其电子邮件和生物。

class App extends Component {
 state = {
   users: []
 }

 async getUser(e) {
   e.preventDefault();
   const username = e.target.elements.username.value;
   const profileResponse = await fetch(`https://api.github.com/users/${username}?client_id=${client_id}&client_secret=${client_secret}`);
   const user = await profileResponse.json();
   this.setState({ users: this.state.users.concat([user]) });
 }

 render() {
 return (
 <div className="App">
   <h1>Search users</h1>
   <p>Enter a username to fetch a user.</p>
   <form onSubmit={this.getUser}>
     <input 
       type="text"
       name="username" 
       placeholder="GitHub username"
     />
     <button>Find User</button>
   </form>

   { this.state.users.length > 0 && this.state.users.map((user) => <p key={user.login}>{user.email, user.bio}</p>) }

 </div>
 );
 }
}
export default App;

错误:

对象作为React子对象无效(找到:带有以下关键字的对象{登录,id,avatar_url,gravatar_id,url,html_url,followers_url,following_url,gissurl,starred_url,subscriptionsURL,organizations_url,repos_url,events_url,received_events_url,类型,site_admin,名称,公司,博客,位置,电子邮件,可出租的,个人简历,public_repos,public_gists,关注者,关注者,created_at,updated_at})。 如果要渲染子级集合,请改用数组。

运行您的示例,我收到以下错误:

Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

getUser转换为固定的箭头函数: getUser = async (e) => {}

进一步阅读: https : //medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56

第二个问题:

渲染中的{user.email, user.bio}无法正常工作,而替换为{user.email} {user.bio}

这是问题:

{user.email, user.bio}

解决方案是:

{user.email}, {user.bio}

另外,您需要确保user.email和user.bio不是对象。

您需要处理从API接收到的响应不是用户对象的情况,例如,如果您要查找的用户不存在。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM