我正在学习reactjs
教程,并且在
将值从一个组件的状态传递到另一个组件时一直遇到问题。
执行组件中Cannot read property 'map' of undefined'
的map
函数时抛出错误CommentList
。
什么会导致的
prop
是undefined
从路过的时候CommentBox
到CommentList
?
// 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'));
这个解决方案有效,但我很好奇。如果我有一个更复杂的 JSON 结构,我是否必须以相同的方式初始化数据对象?似乎应该有更好的方法。谢谢
@Nael 不,你不需要。只需像上面一样包裹块。:)
发生错误是因为
this.props.data
为空。.map
期望在数组上调用。@timothyclifford 感谢您的回答。我知道
this.props.data
是 null 导致地图功能失败。但我不明白的是,教程代码在没有 if 子句的情况下也能工作。为什么this.props.data
教程中不为空?this.props.data
由 AJAX 请求填充。AJAX 是异步的,因此如果在填充数据之前呈现组件,则该组件this.props.data
将为 null,并且您将收到错误消息。这有意义吗?