2017-09-21 151 views
0

我正在使用react来呈现从API中提取的数据。我的代码如下所示:无法读取未定义错误的属性'username'

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

我在渲染功能CONSOLE.LOG(this.state.lists),我从API得到了整个数据,但是当我呈现数据的一部分,我'不能读取属性'的'未定义'错误的用户名。如果我在getInitialState函数中设置了列表['']并且渲染{this.state.lists [0] .username},它可以工作,但是如果我将索引更改为1,我得到了同样的错误。我想这与生命周期功能有关。但我无法弄清楚。从API中获取的数据看起来像这样enter image description here

我一直在为此工作3个小时。希望有人能帮助我。非常感激!

回答

0

的错误是因为最初的渲染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> 

     ); 
    } 
}); 
+0

非常感谢!我得到它的工作!它非常有帮助。我更好地理解了组件生命周期!非常感谢! –

+0

@博黄欢迎您。我建议您阅读https://facebook.github.io/react/docs/react-component.html以获得更好的理解。 – Ved

1

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

发生这种情况,因为render() GET方法的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

'this.state.lists'不是未定义的。它是空的。 – Ved

+0

我的坏它将是空的,因为他已经在构造函数中设置() – squiroid

+0

谢谢!我应付并粘贴了你的代码。我输错了 –

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

这种做法很整洁! –

相关问题