本文介绍了在 React 中渲染嵌套/线程注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下面的数组,我想通过使用 parentId 以线程化的方式呈现 comments.

Given the below array, I'd like to render comments in a threaded manner by making use of parentId.

comments: [
    {
      id: 1,
      parentId: null
    },
    {
      id: 2,
      parentId: 1
    },
    {
      id: 3,
      parentId: 1
    },
    {
      id: 4,
      parentId: 3
    },
    {
      id: 5,
      parentId: 4
    }
  ]

我认为使用下面的组件我可以通过评论递归,但输出不是我所期望的(它似乎正在呈现一个新的

    元素对于每条评论.)我对 react 和 javascript 有点陌生,所以也许我没有正确实现递归,或者 comments 的结构是否应该不同?

    I thought with the below components I'd be able to recurse through the comments, but the output is not what I'd expect (it seems to be rendering a new <ul> element for every comment.) I'm a bit new to react and javascript, so maybe I'm not implementing the recursion correctly, or should comments be structured differently?

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

    推荐答案

    如果您将该列表转换为实际反映注释嵌套层次结构的结构,那么您将可以更轻松地构建用于呈现它们的组件.

    If you turn that list into a structure which actually reflects the nested hierarchy of the comments, then you'll have an easier time building a component for rendering them.

    您可以实现一个函数来进行转换.

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

    You could implement a function to do the conversion.

    这里有一个关于如何从平面结构到嵌套注释列表的想法.完成该实现后,您只需要一个递归的 React 组件.

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

    Here's an idea for how you could go from that flat structure to a list of nested comments. Once you're done with that implementation, all you'd need would be a recursive React component.

    );}

    这篇关于在 React 中渲染嵌套/线程注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:18