からデータを取得できません: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.
componentDidMountで状態を変更しますか?最初のレンダリングで失敗するのは確かですか?私は最初のレンダリングで間違っている可能性のあるものは見当たりません。最初のレンダリングの前にgetInitialStateが実行されます。 –
はい私はajax経由でサーバーからデータをロードすることによってcomponentDicMountの状態を変更しました。 –
あなたのコードは動作します、ここを見てください。 https://jsfiddle.net/4vaq7mL7/1/ componentDidMountのコードを表示します –