我的代码有什么问题?我有错误“ repos.map不是函数”。
我在状态中定义了一个repos数组,然后试图遍历它,但是仍然遇到相同的错误?我想念什么?
这是关于udemy的Brad Traversy项目的一部分,其代码似乎有效,但不是我的;我检查了很多次代码,但仍然收到错误消息。请帮忙!!
class ProfileGithub extends Component {
constructor(props) {
super(props);
this.state = {
clientId: "0b3ee496731*****",
clientSecret: "8a538c0d313959f2a81dab3ca******",
count: 5,
sort: "created: asc",
//*repos array in the state*
repos: []
};
}
componentDidMount() {
const { username } = this.props;
const { count, sort, clientId, clientSecret } = this.state;
fetch(
`https://api.github.com/${username}/repos?per_page=${count}&sort=${sort}&client_id=${clientId}&client_secret=${clientSecret}`
)
.then(res => res.json())
.then(data => {
if (this.refs.myRef) {
this.setState({ repos: data });
}
})
.catch(err => console.log(err));
}
render() {
const { repos } = this.state;
//*trying to loop through it*
const repoItems = repos.map(repo => (
<div key={repo.id} className="card card-body mb-2">
<div className="row">
<div className="col-md-6">
<h4>
<Link to={repo.html_url} className="text-info" target="_blank">
{repo.name}
</Link>
</h4>
<p>{repo.description}</p>
</div>
<div className="col-md-6">
<span className="badge badge-info mr-1">
Stars: {repo.stargazers_count}
</span>
<span className="badge badge-secondary mr-1">
Watchers: {repo.watchers_count}
</span>
<span className="badge badge-success">
Forks: {repo.forks_count}
</span>
</div>
</div>
</div>
));
return (
<div ref="myRef">
<hr />
<h3 className="mb-4">Latest Github Repos</h3>
{repoItems}
</div>
);
}
}
最佳答案
const { repos } = this.state.repos;
您正在对一个对象调用
.map
。 state
是一个对象,repos
是state
的成员。但是,如果要映射对象
state
,则必须执行以下操作:const repoItems = Object.keys(repos).map( repoKey => {
// Now you are using the keys of the object as an array
// so you can access each object like this:
// { repos[repoKey].member_name }
// for instance, in your code above, the first line in the map would be this:
<div key={repo[repoKey].id} className="card card-body mb-2">
// ...and then later...
<Link to={repo[repoKey].html_url} className="text-info" target="_blank">
{repo[repoKey].name}
</Link>
})