错误:无法读取未定义的属性“地图" [英] Error : Cannot read property 'map' of undefined
问题描述
我正在学习 reactjs
教程,但在
将值从一个组件的状态传递到另一个组件时,我一直遇到问题.
错误Cannot read property 'map' of undefined'
执行 CommentList
组件中的 map
函数时抛出.
当从 CommentBox
传递到 CommentList
时,什么会导致 prop
成为 undefined
?
//第一个组件var CommentList = React.createClass({渲染:函数(){var commentNodes = this.props.data.map(function (comment){return <div><h1>{comment.author}</h1></div>;});return {commentNodes};}});//第二个组件var CommentBox = React.createClass({getInitialState: 函数(){返回{数据:[]};},获取注释:函数(){$.ajax({网址:this.props.url,数据类型:'json',成功: function(data){ this.setState({data: data}) }.bind(this),错误:函数(xhr,状态,错误){ console.error(url, status, err.toString()) }.bind(this)});},componentWillMount: 函数(){this.getComments()},渲染:函数(){return <div className="commentBox">{<CommentList data={this.state.data.comments}/>}</div>;}});React.renderComponent( <CommentBox url="comments.json"/>, document.getElementById('content'));
首先,设置更安全的初始数据:
getInitialState : function() {返回{数据:{评论:[]}};},
并确保您的 ajax 数据.
如果您按照上述两个说明操作,例如 Demo,它应该可以工作.
更新:您可以使用条件语句包装 .map 块.
if (this.props.data) {var commentNodes = this.props.data.map(function (comment){返回 (<div>{comment.author}
);});}
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'));
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>
);
});
}
这篇关于错误:无法读取未定义的属性“地图"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!