2015-12-27 16 views
0

我正在參加reactjs教程here,在完成本教程後,我開始修改一點點。我遇到的一個問題是我無法弄清楚如何索引到某個數組(至少它看起來是一個數組)。下面是當數組從服務器得到的代碼:如何索引到已解析的json數組中

componentDidMount: function() { 
    $.ajax({ 
     url: this.props.url, 
     dataType: 'json', 
     cache: false, 
     success: function(data) { 
     this.setState({data: data}); 
     }.bind(this), 
     error: function(xhr, status, err) { 
     console.error(this.props.url, status, err.toString()); 
     }.bind(this) 
    }); 
    }, 

componentDidMount是Reactjs類定義了一個名爲CommentBox類,被解析JSON文件的部分看起來像

[ 
    {id: 1, author: "Pete Hunt", text: "This is one comment"}, 
    {id: 2, author: "Jordan Walke", text: "This is *another* comment"} 
] 

所以現在我試圖改變相同的CommentBox類的render方法來添加一行來打印數據數組的第一個元素。渲染方法變爲

render: function() { 
     return (
      < div className = "commentBox" > 
      {this.state.data[0].toString()} 
      <h1> Comments < /h1> 
      < CommentList data = {this.state.data}/> 
      < CommentForm onCommentSubmit = {this.handleCommentSubmit}/> 
      < /div> 
     ); 
} 

其中我添加的行是{this.state.data[0].toString()}。此行導致錯誤,說明this.state.data[0]未定義。我該如何獲得this.state.data的元素?它不應該只是一個正常的數組,就好像它是由下面的代碼設置的?

this.state.data = [ 
    {id: 1, author: "Pete Hunt", text: "This is one comment"}, 
    {id: 2, author: "Jordan Walke", text: "This is *another* comment"} 
]; 

回答

1

請記住, 「A」 中的 「阿賈克斯」 代表異步; render被稱爲之前您的數據曾經從服務器返回。這意味着第一次調用render時,this.state.data可能未定義(取決於您的getInitialState函數)。

一種常見的方法是添加保持組件從渲染全面警戒值 - 或呈現不同的東西 - 直到數據可用:

getInitialState: function() { 
    return { 
     loaded: false // `loaded` will be our sentinel value 
    }; 
    }, 

    componentDidMount: function() { 
    $.ajax({ 
     url: this.props.url, 
     dataType: 'json', 
     cache: false, 
     success: function(data) { 
     this.setState({ 
      data: data, 
      loaded: true // make sure to set `loaded` to true 
     }); 
     }.bind(this), 
     error: function(xhr, status, err) { 
     console.error(this.props.url, status, err.toString()); 
     }.bind(this) 
    }); 
    }, 

    render: function() { 
     // if the sentinel isn't set, we're not ready 
     if (!this.state.loaded) return <div>Loading...</div>; 

     return (
      < div className = "commentBox" > 
      {this.state.data[0].toString()} 
      <h1> Comments < /h1> 
      < CommentList data = {this.state.data}/> 
      < CommentForm onCommentSubmit = {this.handleCommentSubmit}/> 
      < /div> 
     ); 
    } 

或者,你可以檢查的this.state.data值(或其他適當的東西)來確定數據是否準備好呈現或不。

+0

這固定了它。我之前並沒有使用ajax,所以我不知道它是如何工作的。 –