2016-08-04 39 views
0

からデータを取得できません:getInitialState()私は、次のReactJSコード持っている状態で反応

var CommentList = React.createClass({ 

     render: function(){ 

     var commentNodes = this.props.data.map(function(comment){ 

      return (
      <Comment author={comment.author} key={comment.id}> 
       {comment.text} 
      </Comment> 

     ); 

     }); 

     return (
      <div className="commentList"> 
      {commentNodes} 
      </div> 
     ); 

     } 

    }); 

そしてCommentBoxで....

var CommentBox = React.createClass({ 

     loadCommentFromServer: 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) 

     }); 

     }, 

    }, 
    getInitialState: function() { 

     return { 
     data: [] 
     }; 

    }, 

    componentDidMount: function() { 

     this.loadCommentFromServer(); 

     setInterval(this.loadCommentFromServer, this.props.pollInterval); 

    }, 

    render: function() { 

     return ( 
     <div className = "commentBox" > 
      <h1> Comments </h1> 
      <CommentList data ={ this.state.data } /> 
      <CommentForm /> 
     </div> 
    ); 

    } 

}); 

を、私はすでにデータ用とに値を割り当てますCommentListは、stateから値を取得するプロパティデータも追加します。私が実行しようとすると

、私はこのエラーを得た:

Cannot read property 'map' of undefined in CommentList.

+2

componentDidMountで状態を変更しますか?最初のレンダリングで失敗するのは確かですか?私は最初のレンダリングで間違っている可能性のあるものは見当たりません。最初のレンダリングの前にgetInitialStateが実行されます。 –

+0

はい私はajax経由でサーバーからデータをロードすることによってcomponentDicMountの状態を変更しました。 –

+0

あなたのコードは動作します、ここを見てください。 https://jsfiddle.net/4vaq7mL7/1/ componentDidMountのコードを表示します –

答えて

0

あなたは、単にあなたが戻ってjQuery.ajaxから必要なデータを取得されていませんように見えます。

 success: function(data) { 
     // before setting state, log here and find out what data is 
     // it could need to be turned into JSON? data = data.toJSON(); 
     // or simply this to be safe 
     data = data || []; 

     this.setState({ 
      data: data 
     }); 

     } 
+0

このデータまたは応答データは配列ではありません。 – zangrafx

+0

はまだエラーになります。 –

関連する問題