猿问

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

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

        ]

      }

    ]

  }

]

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


缥缈止盈
浏览 108回答 2
2回答

蝴蝶不菲

您可以递归地渲染它const data = [&nbsp; {&nbsp; &nbsp; "value": "awesome",&nbsp; &nbsp; "comments": [&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "value": "thanks"&nbsp; &nbsp; &nbsp; &nbsp; "comments": null&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "value": "really awesome",&nbsp; &nbsp; &nbsp; &nbsp; "comments": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "value": "thanks again",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "comments": null&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ]&nbsp; }]const CommentItem = (props) => {&nbsp; return (&nbsp; &nbsp; <div>{props.item.value}</div>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; Array.isArrray(props.item.comments) &&&nbsp;&nbsp; &nbsp; &nbsp; props.item.comments.length >= 1 &&&nbsp; &nbsp; &nbsp; props.comments.map(comment => (&nbsp; &nbsp; &nbsp; &nbsp; <CommentItem item={comment.comments}/>&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }&nbsp; )}return data.map(comment => <CommentItem item={comment}/>)

qq_花开花谢_0

您将使用递归函数。递归意味着函数调用自身,或者在 React 的情况下,是一个将自身作为子元素返回的组件。这是一个将值呈现为段落元素的示例,然后呈现子注释。function Comment(props) {&nbsp; &nbsp; return (<>&nbsp; &nbsp; &nbsp; &nbsp; <p>{props.value}</p>&nbsp; &nbsp; &nbsp; &nbsp; {props.comments ?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; props.comments.map(comment => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return <Comment comments={comment.comments} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; : null}&nbsp; &nbsp; </>)}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答