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!
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 .