Tengo un árbol de componentes que se ve así:
<Profile> <FollowersAndFollowing> <Overlay> {children} </Overlay> </FollowersAndFollowing> </Profile> En <Profile/> tengo un estado que contiene un valor booleano:
const [showFollowers, setShowFollowers] = useState(false)
Estoy tratando de canalizar este estado a todos mis componentes. En mi <Profile/> tengo estas dos funciones.
const handleShowFollowers = () => setShowFollowers(true) const handleHideFollowers = () => setShowFollowers(false) console.log('from profile', showFollowers) // logs true, then logs falseEN PERFIL
{showFollowers ? <FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} /> : null}SEGUIDORES Y SEGUIDORES
const FollowersAndFollowing = ({ showFollowers, handleHideFollowers }) => { console.log('from followers', showFollowers) // logs true, then logs nothing at all return ( <Overlay isShowing={showFollowers} currentTopPosition={0}> <h1>followers and following</h1> <button onClick={handleHideFollowers}>BACK</button> </Overlay> ) }CUBRIR
const Overlay = ({ isShowing, children, currentTopPosition }) => { console.log('from overlay', isShowing) // logs true, then logs nothing at all useEffect(() => { if (isShowing) { document.body.style.overflow = "hidden"; } else { document.body.style.overflow = "visible"; } }, [isShowing]) return ( <div className={isShowing ? overlayStyles.showOverlay : overlayStyles.overlay} style={{ top: `${currentTopPosition}px` }}> {children} </div> ) } Cuando handleShowFollowers desde mi componente <Profile/> , veo showFollowers como verdadero para los tres componentes.
Sin embargo, cuando handleHideFollowers desde el componente <FollowersAndFollowing/> , veo que showFollowers a falso en el componente principal (perfil), pero no en ninguno de los otros dos componentes. ¿Qué podría estar causando esto?
Esta línea es el problema:
{showFollowers ? <FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} /> : null} Si showFollowers es falso, entonces su componente FollowersAndFollowing no se procesará en absoluto, es por eso que console.log s no registra.
Si lo cambias a solo esto:
<FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} />Luego puede manejar los elementos ocultos más profundamente dentro de los componentes secundarios y debería funcionar bien.