4
鑑於下面的數組,我想通過使用parentId
以線程方式呈現comments
。在React中渲染嵌套/線索註釋
comments: [
{
id: 1,
parentId: null
},
{
id: 2,
parentId: 1
},
{
id: 3,
parentId: 1
},
{
id: 4,
parentId: 3
},
{
id: 5,
parentId: 4
}
]
我想用下面的成分我能夠通過意見遞歸,但輸出是不是我期望的是什麼(它似乎呈現每一個評論新<ul>
元素。)我'有點新的反應和JavaScript,所以也許我沒有正確實施遞歸,或應該是不同的結構?
const Comment = (props) => (
<li>
{props.comment.id}
{props.comment.children.length > 0 ?
<Comments comments={props.comment.children}/>
: null }
</li>
);
const Comments = (props) => (
<ul>
{props.comments.map((comment) => {
comment.children = _.filter(props.comments, {'parentId': comment.id});
return <Comment key={comment.id} comment={comment}/>
})}
</ul>
);
真棒。 我只想代替 parent.children =(parent.children || [])。push(comment); 由 (parent.children = parent.children || [])。push(comment); –