[英]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.