Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
Ganchos de reacción: hijos de componentes mapeados dinámicamente y estado independiente del padre

Estoy recopilando publicaciones (llamadas latestFeed ) de mi backend con una llamada a la API. Todas estas publicaciones están asignadas a componentes y tienen comentarios. Los comentarios deben abrirse y cerrarse independientemente uno del otro. Controlo esta mecánica asignando un estado llamado showComment a cada comentario. showComment se genera en el nivel principal según lo dictan las Reglas de Hooks.

Aquí está el componente padre.

 import React, { useState, useEffect } from "react"; import { getLatestFeed } from "../services/axios"; import Child from "./Child"; const Parent= () => { const [latestFeed, setLatestFeed] = useState("loading"); const [showComment, setShowComment] = useState(false); useEffect(async () => { const newLatestFeed = await getLatestFeed(page); setLatestFeed(newLatestFeed); }, []); const handleComment = () => { showComment ? setShowComment(false) : setShowComment(true); }; return ( <div className="dashboardWrapper"> <Child posts={latestFeed} showComment={showComment} handleComment={handleComment} /> </div> ); }; export default Parent;

latestFeed se construye junto con showComment . Después latestFeed regresa con una serie de publicaciones en el useEffect , se pasa al programa secundario aquí:

 import React, { useState } from "react"; const RenderText = ({ post, showComment, handleComment }) => { return ( <div key={post._id} className="postWrapper"> <p>{post.title}</p> <p>{post.body}</p> <Comments id={post._id} showComment={showComment} handleComment={() => handleComment(post)} /> </div> ); }; const Child = ({ posts, showComment, handleComment }) => { return ( <div> {posts.map((post) => { <RenderPosts posts={posts} showComment={showComment} handleComment={handleComment} />; })} </div> ); }; export default Child;

Sin embargo, cada vez que handleComments , todos los comentarios se abren para todas las publicaciones. Me gustaría que fueran solo el comentario en el que se hizo clic.

¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Está intentando usar un solo estado donde afirma que quiere múltiples estados independientes. Defina el estado directamente donde lo necesite.

Para hacer eso, elimine

 const [showComment, setShowComment] = useState(false); const handleComment = () => { showComment ? setShowComment(false) : setShowComment(true); };

de Parent , elimine los showComment y handleComment de Child y RenderText , luego agregue

 const [showComment, handleComment] = useReducer(state => !state, false);

para RenderText .

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda