簡體   English   中英

React map got item未定義

[英]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應該有意義。 找不到我的錯。

https://jsfiddle.net/pvg1hg0s/

您需要將json.items更改為json

this.setState({repo: json})

這是一個更新的jsfiddle。

您的componentWillMount方法應如下所示

fetch('https://api.github.com/users/abc/repos')
.then(response => {
  return response.json()
}).then(json => {
  this.setState({repo: json})
})

原因是您作為json引用的響應沒有任何item鍵,因此返回undefined 它實際上是返回一個數組,然后你可以用map循環。 首先,您需要使用setStatejson的值設置為API調用的響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM