繁体   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