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

时间:2017-09-21 18:20:00

标签: javascript reactjs

我使用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获取了整个数据,但是当我渲染部分数据时,我得到了“无法读取属性”# 39;用户名&#39;未定义的&#39;错误。如果我在getInitialState函数中设置列表:[&#39;&#39;]并渲染{this.state.lists [0] .username},它可以工作,但如果我将索引更改为1,我会得到相同的错误。我想它与生命周期功能有关。但我无法弄明白。从API获取的数据类似于enter image description here

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

3 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为this.state.lists将在第一次未定义。 使用以下代码首次绕过它

这种情况正在发生,因为render()方法在componentDidMount()之前被调用,而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> }
);

答案 1 :(得分:1)

错误是因为初始渲染componentDidMount()不会有任何数据。 初始渲染后调用render: function(){ console.log(this.state.lists); return( <div>{this.state.lists.length >0 ?this.state.lists[0].username:null}</div> ); } }); 生命周期方法。

{{1}}

答案 2 :(得分:0)

问题是因为在渲染之前没有提取数据。

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