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 beundefined
when passing fromCommentBox
into theCommentList
?
// First component var CommentList = React.createClass({ render: function() { var commentNodes = this.props.data.map(function (comment){ return <div><h1>{comment.author}</h1></div>; }); return <div className="commentList">{commentNodes}</div>; } }); // Second component 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 <div className="commentBox">{<CommentList data={this.state.data.comments}/>}</div>; } }); React.renderComponent( <CommentBox url="comments.json" />, document.getElementById('content'));
The "cannot read property 'map' of undefined" error occurs when we call the map() method on an undefined value, most often when the map method is called before the data from an API request has arrived. To solve the error, initialize the value you're mapping over to an empty array.
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
What Causes TypeError: Cannot Read Property of Undefined. Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects.
In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.
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 ( <div> <h1>{comment.author}</h1> </div> ); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With