繁体   English   中英

无法读取未定义错误的属性“用户名”

[英]Cannot read property 'username' of undefined error

我正在使用react渲染从API获取的数据。 我的代码如下所示:

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'));

我在render函数中使用console.log(this.state.lists),我从API中获得了全部数据,但是当我渲染数据的一部分时,我得到了“无法读取属性'username'的未定义'错误。 如果我在getInitialState函数中设置列表:['']并呈现{this.state.lists [0] .username},它可以工作,但是如果将索引更改为1,则会出现相同的错误。 我想这与生命周期功能有关。 但我不知道。 从API提取的数据如下所示 在此处输入图片说明

我已经为此工作了3个小时。 希望有人可以帮助我。 非常感激!

发生这种情况是因为this.state.lists将是第一次未定义。 使用下面的代码第一次使其绕过

发生这种情况是因为在componentDidMount()之前调用了render()方法,并且您的this.state.lists[] ,因此this.state.list[0]将是undefined ,它将在的帮助下进行设置this.setState()直到this.state.lists为空

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

该错误是因为初始渲染this.state.lists将没有任何数据。 初始渲染后将调用componentDidMount()生命周期方法。

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

        );
  }
});

问题是因为在渲染之前尚未获取数据。

    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'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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