gpt4 book ai didi

javascript - 如何使用react从github API获取用户仓库?

转载 作者:行者123 更新时间:2023-12-03 02:02:35 25 4
gpt4 key购买 nike

我有一个 React 应用程序,可以使用 github api 在 github 上搜索用户。我有搜索用户的部分工作正常,但是当我添加一个组件来显示用户的存储库时,它只显示用户信息,并且控制台给出此错误: Uncaught (in Promise) TypeError:无法读取未定义的属性“值”

这是我的代码:

    class GitHubSearch extends React.Component {
constructor(props){
super(props);
this.state = {
username: '',
userrepo: '',
};
}

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

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

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

let repo = await this.getUserRepo(this.refs.userrepo.value);
this.setState({ name: repo.name,
description: repo.description,
git_url: repo.git_url,
stargazers_count: repo.stargazers_count,
forks_count: repo.forks_count,
open_issues_count: repo.open_issues_count,
size: repo.size,

})

}

render() {
let user;
if(this.state.username) {
user =
<div className="resultBadge">
<img src={this.state.avatar_url}/>
<p className="userInfo">
Username: <br/>
{this.state.username}
</p>
<p className="followerInfo">
{this.state.followers} Followers
</p>
<p className="followingInfo">
Following {this.state.following} users
</p>
</div>
}

let repo;
if(this.state.userrepo) {
repo =
<div className="repoResults">
<p>
{this.state.name}
</p>
</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>
<p>
{repo}
</p>
</div>
);
}
}


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

HTML 是:

这里是不是少了什么?

最佳答案

实际上,您没有 userrepo 引用。

也许,您应该使用相同的引用来获取存储库,因为您的 getUserRepo 获取用户名属性而不是存储库名称。

因此您的 getUserRepo 函数应如下所示:

let repo = await this.getUserRepo(this.refs.username.value);
this.setState({ name: repo.name,
description: repo.description,
git_url: repo.git_url,
stargazers_count: repo.stargazers_count,
forks_count: repo.forks_count,
open_issues_count: repo.open_issues_count,
size: repo.size,

})

关于javascript - 如何使用react从github API获取用户仓库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49947330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com