2016-08-30 32 views
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.commentsimmutable.Map

如何映射immutable.Mapthis.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> 

爲什麼就是它?

回答

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>);

+0

這是因爲當你使用Immutable.Map創建對象是隻取第一級爲不可變對象。所以,comments.get(「3」)會給出一個對象{「id」:3,「author」:「我」,「text」:「這是一個評論!」}。但是,返回的對象是在第二級,它不是不可變的。所以,像set(),get()等不可變函數不適用於它們。 – Samu

+0

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