0
,我有以下的正則表達式組件的值:地圖相聯繫的數組
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
)首先將其值轉換爲列表,其中我只是對這些值進行迭代。
UPDATE:
我得到一個錯誤,說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>
爲什麼就是它?
這是因爲當你使用Immutable.Map創建對象是隻取第一級爲不可變對象。所以,comments.get(「3」)會給出一個對象{「id」:3,「author」:「我」,「text」:「這是一個評論!」}。但是,返回的對象是在第二級,它不是不可變的。所以,像set(),get()等不可變函數不適用於它們。 – Samu
const comments = fromJS({「{」id:3,「author」:「Me」,「text」:「This is one comment!」)), 「4」:Map {「id」:4,「author」:「You」,「text」:「This is more more!」)), 「5」:Map({「id」:5,「author」:「Bar 「,」text「:」這是一條評論!「)), .... }) 上面的代碼對你來說可以正常工作,但是對於第二級中所有值的映射來說都很麻煩。這就是Immutable.fromJS()派上用場的地方。它一次完成深度轉換。請在創建對象而不是Map時檢查我以前使用的fromJS示例。 – Samu