我的代码有什么问题?我有错误'repos.map不是一个函数'。 我在我的状态中定义了一个repos数组,然后我试图循环它,但我仍然是同样的错误?我错过了什么? 这是Brad Traversy关于udemy的项目的一部分,它的代码似乎工作但不是我的;我检查了很多次代码,但仍然收到错误。请帮忙!!
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>
})
正如Thiago Sun所指出的,这里的数据参数可能不是数组。您可能需要验证。
.then(data => {
if (this.refs.myRef) {
this.setState({ repos: data });
}
})
非常感谢你们提出的建议,但问题在于获取网址,我错过了一些东西......非常感谢