Javascript 未定义React map Get项
我得到的回购协议没有定义。但是我可以看到console.log(json.items)中的数组Javascript 未定义React map Get项,javascript,reactjs,Javascript,Reactjs,我得到的回购协议没有定义。但是我可以看到console.log(json.items)中的数组 const githubRepo = React.createClass({ getInitialState(){ return { repo: [] } }, componentWillMount(){ fetch('https://api.github.com/users/abc/repos') .then(response => {
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>
)
}
})
const githubRepo=React.createClass({
getInitialState(){
返回{
回购:[]
}
},
组件willmount(){
取('https://api.github.com/users/abc/repos')
。然后(响应=>{
返回response.json()
})。然后(json=>{
this.setState({repo:json.items})
})
},
render(){
返回(
{
this.state.repo.map(repo=>
- {repo.name}
)
}
)
}
})
我的地图功能有问题吗?componentWillMount表示在渲染前执行,hmm take应该有意义。找不到我的错误
您需要将
json.items
更改为json
this.setState({repo: json})
您的组件willmount
方法应该如下所示
fetch('https://api.github.com/users/abc/repos')
.then(response => {
return response.json()
}).then(json => {
this.setState({repo: json})
})
原因是您引用为json
的响应没有任何带有项的键
,因此返回的是未定义的
。它实际上返回了一个数组,您可以使用map
循环该数组。首先,您需要使用setState
将json
的值设置为API调用的响应