如何映射具有未知嵌套级别的数组?

How to map an array with unknown nesting levels?

我有一个可以有答案的评论数组,所以数组的每个元素(评论)都可以有嵌套元素(评论)并且嵌套级别是未知的,但是我需要在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
        ]
      }
    ]
  }
]

希望这个例子对您有所帮助。

您将使用递归函数。递归意味着函数调用自身,或者在 React 的情况下,一个 returns 本身作为子组件的组件。

这是一个将值呈现为段落元素,然后呈现子评论的示例。

function Comment(props) {
    return (<>
        <p>{props.value}</p>
        {props.comments ? 
            props.comments.map(comment => {
                return <Comment comments={comment.comments} />
            })
        : null}
    </>)
}

你可以递归渲染它

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