javascript - 在 React 中呈现嵌套/线程评论

标签 javascript recursion reactjs

给定下面的数组,我想渲染 comments通过使用 parentId 以线程方式.

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

我认为使用以下组件我可以通过评论递归,但输出不是我所期望的(它似乎为每个评论呈现一个新的 <ul> 元素。)我是React 和 javascript 有点新,所以也许我没有正确实现递归,或者应该 comments结构不同?

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

最佳答案

如果您将该列表转换为实际反射(reflect)评论嵌套层次结构的结构,那么您将更容易构建用于呈现它们的组件。

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

关于javascript - 在 React 中呈现嵌套/线程评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829778/

相关文章:

javascript - DevExtreme React 网格

javascript - jquery中switch和if中为什么推荐使用else if

java - 波斯地毯递归

javascript - 我如何默认隐藏侧边栏?

javascript - 在 Extjs 中加载视口(viewport)之前,非 MVC 创建的商店不会实例化

javascript - 在 javascript 中使用复杂的揭示模块模式

java - 循环递归在返回语句之前不增加其值

python - 提供唯一 ID 时超出最大递归深度

javascript - 每当我点击连接元掩码按钮时,为什么它会连接 coinbase 钱包?

android - 类型错误 : null is not an object (evaluating 'RNGestureHandlerModule.default.Direction' )