首页 > 解决方案 > 如何使用 reactjs 构建评论回复结构?

问题描述

我正在研究 react js 应用程序并构建评论回复结构。API 向我返回了一组评论,但它不在评论层次结构中。我的 API 响应是这样的:

review: {_id: 35,email: "test@gmail.com", review: "Shavon B does an AMAZING job!!  I had another fant…e taking care of my home.  Shavon is a rock star!"}
comments: [
    0: {_id: 36, status: 1, email: "neha@shandil.com", review: "Shavon B does an AMAZING job!!  I had another fant…e taking care of my home.  Shavon is a rock star!", parent_id: 35, reply_to:35}
    1: {_id: 37, status: 1, email: "archana@gmail.com", review: " Thank you for sharing your review of your home cl…e taking care of my home.  Shavon is a rock star!", parent_id: 35, reply_to:36}
    2: {_id: 39, status: 1, email: "radhika@dummy-url.com", review: "Shavon B does an AMAZING job!!  I had another fant…e taking care of my home.  Shavon is a rock star!", parent_id: 35, reply_to:37}
    3: {_id: 40, status: 1, email: "archi@123.com", review: "good", parent_id: 35, reply_to:36}
    4: {_id: 41, status: 1, email: "test@test.com", review: "Testing", parent_id: 35, reply_to:35}
]

这里 parent_id 表示这些是任何 id 为 35 的博客的评论,reply_to 表示这是对该特定评论 _id 的回复,例如索引 1 处的数组是索引 0 处评论的回复。

现在,我在列表末尾也收到了新的回复。现在我想在他们的层次结构中显示所有评论。现在的问题是我得到了一个包含所有评论和回复的简单数组,如何在层次结构中显示它们。这是否可以在两者之间推送 HTML,请建议我一个解决方案,我想显示最多两个级别的评论。

标签: reactjs

解决方案


您需要将评论转换为树形结构,并且需要编写递归逻辑来处理评论。

将平面列表转换为树的函数:

function unflatten(arr) {
  var tree = [],
      mappedArr = {},
      arrElem,
      mappedElem; 

  // First map the nodes of the array to an object -> create a hash table.
  for(var i = 0, len = arr.length; i < len; i++) {
    arrElem = arr[i];
    mappedArr[arrElem._id] = arrElem;
    mappedArr[arrElem._id]['children'] = [];
  }


  for (var id in mappedArr) {
    if (mappedArr.hasOwnProperty(id)) {
      mappedElem = mappedArr[id];
      // If the element is not at the root level, add it to its parent array of children.
      if (mappedElem.parent_id) {
        mappedArr[mappedElem['parent_id']]['children'].push(mappedElem);
      }
      // If the element is at the root level, add it to first level elements array.
      else {
        tree.push(mappedElem);
      }
    }
  }
  return tree;
} 

这是递归组件和树数据的工作 POC: https ://stackblitz.com/edit/react-7jhe22?file=index.js

POC 显示自动添加随机评论以模仿用户添加评论的行为。这也显示了如何在评论数组的末尾追加,并在unflatten函数的帮助下仍然生成评论视图。由于这是递归的,您可以回复任何评论!


推荐阅读