[英]React map got item is not defined
I got repo is not defined. 我得到的回购没有定义。 But I console.log(json.items) I can see the arrays.
但我的console.log(json.items)我可以看到数组。
const githubRepo = React.createClass({
getInitialState(){
return {
repo: []
}
},
componentWillMount(){
fetch('https://api.github.com/users/abc/repos')
.then(response => {
return response.json()
}).then(json => {
this.setState({repo: json.items})
})
},
render(){
return(
<div>
<ul>
{
this.state.repo.map(repo =>
<li>{repo .name}</li>
)
}
</ul>
</div>
)
}
})
Something is wrong with my map function? 我的地图功能出了什么问题? componentWillMount means execute before render, hmm take should make sense.
componentWillMount意味着在渲染之前执行,hmm take应该有意义。 Can't find my mistake.
找不到我的错。
https://jsfiddle.net/pvg1hg0s/ https://jsfiddle.net/pvg1hg0s/
You need to change json.items
to just json
. 您需要将
json.items
更改为json
。
this.setState({repo: json})
Here is an updated jsfiddle. 这是一个更新的jsfiddle。
Your componentWillMount
method should look like this 您的
componentWillMount
方法应如下所示
fetch('https://api.github.com/users/abc/repos')
.then(response => {
return response.json()
}).then(json => {
this.setState({repo: json})
})
The reason is that the response which you are referencing as json
does not have any keys with item
hence this was returning undefined
. 原因是您作为
json
引用的响应没有任何item
键,因此返回undefined
。 It is actually returning an array which you can then loop over with map
. 它实际上是返回一个数组,然后你可以用
map
循环。 Firstly you will need to set the value of json
to the response of the API call using setState
. 首先,您需要使用
setState
将json
的值设置为API调用的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.