【问题标题】:Count number of Children in recursive react component计算递归反应组件中的子项数
【发布时间】:2021-12-29 19:19:27
【问题描述】:

我正在开发一个评论系统,并使用递归方法来显示父子 cmets。当我删除一个孩子时,我想更新其父母的孩子 cmets 的计数。

//json数据 数据 = [{ 名称:'父母1', 孩子评论:[{ 名称:'Child1', 文本:'子评论1' }, { 名称:'Child2', 文本:'子评论2' }] },{ 名称:'父母2', 孩子评论:[{ 名称:'Child1', 文本:'子评论1' }, { 名称:'Child2', 文本:'子评论2' }] }]

const Comment = ({ item }) => {
  const childComment = item

 //delete child element and update the parent count 
  const deleteChildComment =(item) => {
    
  }

  return childComment && (
    <>
      {name}
      Children count : {childComments.length}
                 <Button
                  className={styles.replies}
                  onClick={() => {
                    setNewCommentAdded(false)
                    deleteChildComment(childComment)
                  }}
                > Delete This comment </Button>
      {childComments && items.map((item) => (
        <Comment item={item} />
      ))}
    </>
  )
}

【问题讨论】:

    标签: javascript reactjs react-native jsx


    【解决方案1】:

    计算孩子的数量是个坏主意,会使事情变得过于复杂。 只需使用您用来生成评论组件的数据即可。

    通常,始终让 UI 代表数据。不要试图从你的 UI 布局中获取数据。

    例如

    commentList.map((comment) => (<Comment childCount={comment.children.length}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多