如何映射一个具有未知嵌套层级的数组?

3
我有一个评论数组,其中可以包含回复,因此数组的每个元素(评论)都可以有嵌套元素(评论),而嵌套级别是未知的。但我需要在ReactJs中呈现此数组以显示这些评论及其嵌套级别。
comment 1
-- comment 2
-- comment 3
---- comment 4
-- comment 5
comment 6
-- comment 7

像这样。但我不知道如何实现。

我想看一个使用ReactJs渲染它的例子,但是如何在JavaScript中映射这样的数组的示例也会很有帮助。

我的数组比字符串数组更复杂,但让我们假设它就像这样

[
  {
    "value": "awesome",
    "comments": [
      {
        "value": "thanks"
        "comments": null
      },
      {
        "value": "really awesome",
        "comments": [
          "value": "thanks again",
          "comments": null
        ]
      }
    ]
  }
]

希望这个例子能够帮到您。


我猜你可以自己编写递归解决方案。 - Sarthak Aggarwal
这个回答解决了你的问题吗?如何在React.js中递归地渲染子组件 - user13198697
2个回答

3
你需要使用递归函数。递归意味着函数会调用自身,或者在React中,一个组件会作为子元素返回自己。
这里有一个例子,它将值呈现为段落元素,并呈现子评论。
function Comment(props) {
    return (<>
        <p>{props.value}</p>
        {props.comments ? 
            props.comments.map(comment => {
                return <Comment comments={comment.comments} />
            })
        : null}
    </>)
}

我喜欢它,我会尝试一下。 - Dmitriy Movchaniuk

2

您可以递归地渲染它。

const data = [
  {
    "value": "awesome",
    "comments": [
      {
        "value": "thanks"
        "comments": null
      },
      {
        "value": "really awesome",
        "comments": [
          "value": "thanks again",
          "comments": null
        ]
      }
    ]
  }
]

const CommentItem = (props) => {
  return (
    <div>{props.item.value}</div>
    {
      Array.isArrray(props.item.comments) && 
      props.item.comments.length >= 1 &&
      props.comments.map(comment => (
        <CommentItem item={comment.comments}/>
      )
    }
  )
}

return data.map(comment => <CommentItem item={comment}/>)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接