简体   繁体   中英

Cannot read property 'username' of undefined error

I'm using react to render data fetched from a API. My code looks like this:

var App = React.createClass({

getInitialState : function(){

  return {
      lists: []
  }  
},

componentDidMount: function(){

  fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent')
  .then(function(result){
        return  result.json();
    }).then(function(jsonResult){
        this.setState({
            lists: jsonResult
        });
    }.bind(this));  
  },



render: function(){
    console.log(this.state.lists);
    return(
        <div>{this.state.lists[0].username}</div>

        );
  }
});

ReactDOM.render(<App />, document.getElementById('container'));

I console.log (this.state.lists) in the render function and I got the whole data from the API, but when I render a part of the data, I got the 'Cannot read property 'username' of undefined ' error. If I set lists: [''] in the getInitialState function and render {this.state.lists[0].username}, it works but if I change the index to 1, I got the same error. I guess it has something to do with the lifecycle functions. But I can't figure it out. The data fetched from API looks like this 在此处输入图片说明

I've been working on this for 3 hours. Hope someone could help me out. Much appreciated!

This is happening because this.state.lists will be undefined first time. Use below code to get it bypass for the first time

This is happening because render() method get's called before componentDidMount() and your this.state.lists is [] at that time, hence this.state.list[0] will be undefined It will be going to set with the help of this.setState() till then this.state.lists will be empty

return(
  { this.state.lists.length && <div>this.state.lists[0].username </div> }
);

The error is because for initial rendering this.state.lists will not have any data. componentDidMount() lifecycle method is called after initial rendering.

render: function(){
    console.log(this.state.lists);
    return(
        <div>{this.state.lists.length >0 ?this.state.lists[0].username:null}</div>

        );
  }
});

The problem is because the data has not been fetched before rendering.

    componentDidMount(){
      fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent')
          .then(function(result){
          return  result.json();
         }).then(function(jsonResult){
            this.setState({
               lists: jsonResult
            });
        }.bind(this));  
    }

componentWillReceiveProps(nextProps) {
   this.renderView();
}

renderView = () => {
 if (this.state.lists){
      return <div>{this.state.lists[0].username}</div>
 } else { return <div><p>loading</p></div>
}
render() {
   return (
  {this.renderView()}
)
ReactDOM.render(<App />, document.getElementById('container'));

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