Wednesday 13 February 2019

reactjs - Cannot read property 'map' of undefined



I'm following the reactjs tutorial, and I keep running into an issue when passing the value from the state of one component into another component. The error 'Cannot read property 'map' of undefined' is thrown when the map function in the CommentList component is executed. What would cause the prop to become undefined when passing from the CommentBox into the CommentList?



  var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function (comment){

return (

{comment.author}



);
});
return (

{commentNodes}


);
}
});

var CommentBox = React.createClass({
getInitialState: function(){
return {data: []};
},
getComments: function(){
$.ajax({

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

componentWillMount: function(){
this.getComments()
},
render: function(){
return (

{/*this.state.data.comments*/}
{}

);

}
});

React.renderComponent(
,
document.getElementById('content')
);

Answer



First of all, set more safe initial data:




getInitialState : function() {
return {data: {comments:[]}};
},


And ensure your ajax data.



It should work if you follow above two instructions like Demo.




Updated: you can just wrap the .map block with conditional statement.



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

{comment.author}



);
});

}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...