我的代码有什么问题?我有错误“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>
})
关于javascript - TypeError : repos. 映射不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112231/