[英]React map got item is not defined
我得到的回購沒有定義。 但我的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>
)
}
})
我的地圖功能出了什么問題? componentWillMount意味着在渲染之前執行,hmm take應該有意義。 找不到我的錯。
您需要將json.items
更改為json
。
this.setState({repo: json})
您的componentWillMount
方法應如下所示
fetch('https://api.github.com/users/abc/repos')
.then(response => {
return response.json()
}).then(json => {
this.setState({repo: json})
})
原因是您作為json
引用的響應沒有任何item
鍵,因此返回undefined
。 它實際上是返回一個數組,然后你可以用map
循環。 首先,您需要使用setState
將json
的值設置為API調用的響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.