简体   繁体   中英

React map got item is not defined

I got repo is not defined. But I console.log(json.items) I can see the arrays.

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. Can't find my mistake.

https://jsfiddle.net/pvg1hg0s/

You need to change json.items to just json .

this.setState({repo: json})

Here is an updated jsfiddle.

Your componentWillMount method should look like this

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 . It is actually returning an array which you can then loop over with map . Firstly you will need to set the value of json to the response of the API call using setState .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM