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

IT技术 javascript arrays json reactjs rendering
2021-05-23 01:20:22

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

我希望这个例子会有所帮助。

2个回答

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

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

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