Estoy trabajando en un sistema de comentarios y utilicé un enfoque recursivo para mostrar los comentarios de padres e hijos. Cuando elimino un niño, quiero actualizar el recuento de comentarios de niños para su padre.
//datos json data = [{ nombre: 'Padre1', childComments: [{ nombre: 'Child1', text:'child comment1' }, { name: 'Child2', text:'child comment2' }] },{ nombre: 'Parent2', childComments: [{ name: 'Child1', text:'child comment1' }, { name: 'Child2', text:'child comment2' }] }]
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} /> ))} </> ) }
Contar a los niños sería una mala idea y complicaría demasiado las cosas. Simplemente use los datos que usa para generar el componente de comentarios.
Como regla general, siempre haga que una interfaz de usuario represente datos. No intente derivar datos de su diseño de interfaz de usuario.
p.ej
commentList.map((comment) => (<Comment childCount={comment.children.length}));