我正在使用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中獲取的數據看起來像這樣
我一直在爲此工作3個小時。希望有人能幫助我。非常感激!
非常感謝!我得到它的工作!它非常有幫助。我更好地理解了組件生命週期!非常感謝! –
@博黃歡迎您。我建議您閱讀https://facebook.github.io/react/docs/react-component.html以獲得更好的理解。 – Ved