我有以下正则表达式组件:
const CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList comments={this.props.comments}/>
<CommentForm />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
return <div className="commentList">
{this.props.comments.toList().map(comment =>
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
)}
</div>
}
});
this.props.comments
中的数据如下:
{"comments":{"3":{"id":3,"author":"Me","text":"This is one comment!"},"4":{"id":4,"author":"You","text":"This is one more comment!"},"5":{"id":5,"author":"Bar","text":"This is one comment!"},"6":{"id":6,"author":"Foo","text":"This is one more comment!"},"7":{"id":7,"author":"Baz","text":"This is one comment!"},"8":{"id":8,"author":"Boo","text":"This is one more comment!"}}}
请注意,this.props.comments
是immutable.Map
。
如何映射immutable.Map
this.props.comments
中的值,而不是首先通过(toList
)将其值转换为列表,而只是迭代值。
更新
我收到一条错误,说我在尝试时未定义comment.get:
const CommentList = ({comments}) =>
<div className="commentList">
{comments.map(comment =>
<Comment author={comment.get('author')} key={comment.get('id')}>
{comment.text}
</Comment>)}
</div>
但是,以下代码按预期工作:
const CommentList = ({comments}) =>
<div className="commentList">
{comments.valueSeq().map( (comment) =>
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
)}
</div>
为什么?
答案 0 :(得分:1)
Immutable.Map对象默认具有地图功能。您可以像遍历不可变列表一样迭代它。唯一需要注意的是,结果将是一个具有与迭代元素相同键的Map,但是它们的相应值仍然是我们从map()回调函数返回的值。由于Map没有深度转换对象,我建议使用fromJS()。请在此处查看此主题:Difference between fromJS and Map。
您可以尝试以下代码:
const comments = fromJS({
"3":{"id":3,"author":"Me","text":"This is one comment!"},
"4":{"id":4,"author":"You","text":"This is one more comment!"},
"5":{"id":5,"author":"Bar","text":"This is one comment!"},
"6":{"id":6,"author":"Foo","text":"This is one more comment!"},
"7":{"id":7,"author":"Baz","text":"This is one comment!"},
"8":{"id":8,"author":"Boo","text":"This is one more comment!"}
})
comments.map(comment =>
<Comment author={comment.get('author')} key={comment.get('id')} >
{comment.get('text')}
</Comment>);
&#13;