2017-09-21 148 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

這種做法很整潔! –

相關問題