gpt4 book ai didi

javascript - 映射关联数组的值

转载 作者:行者123 更新时间:2023-12-03 06:13:23 25 4
gpt4 key购买 nike

我有以下正则表达式组件:

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>

这是为什么?

最佳答案

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

关于javascript - 映射关联数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com