2016-04-24 58 views
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> 
); 

回答

9

如果你把這個列表插入的真實反映意見的嵌套層次結構,那麼你就可以更輕鬆地構建一個組件,用於渲染他們。

[ 
    { 
    id: 1, 
    children: [ 
     { id: 2, children: [] }, 
     { id: 3, children: [ ... ] } 
    ] 
    } 
] 

您可以實現一個函數來完成轉換。

function nestComments(commentList) { 
    const commentMap = {}; 

    // move all the comments into a map of id => comment 
    commentList.forEach(comment => commentMap[comment.id] = comment); 

    // iterate over the comments again and correctly nest the children 
    commentList.forEach(comment => { 
    if(comment.parentId !== null) { 
     const parent = commentMap[comment.parentId]; 
     parent.children = (parent.children || []).push(comment); 
    } 
    }); 

    // filter the list to return a list of correctly nested comments 
    return commentList.filter(comment => { 
    return comment.parentId === null; 
    }); 
} 

下面是如何從平面結構到嵌套註釋列表的一個想法。一旦你完成了這個實現,你需要的只是一個遞歸的React組件。

function Comment({ comment }) { 
    const nestedComments = (comment.children || []).map(comment => { 
    return <Comment comment={comment} />; 
    }); 

    return (
    <div key={comment.id}> 
     <span>{comment.text}</span> 
     <a href={comment.author.url}>{comment.author.name}</a> 
     {nestedComments} 
    </div> 
); 
} 
+1

真棒。 我只想代替 parent.children =(parent.children || [])。push(comment); 由 (parent.children = parent.children || [])。push(comment); –