繁体   English   中英

state 的一块在父组件中发生变化但在子组件中没有变化 React

[英]Piece of state changes in parent component but not in child components React

我有一个看起来像这样的组件树:

<Profile>
   <FollowersAndFollowing>
      <Overlay>
         {children}
      </Overlay>
   </FollowersAndFollowing>
</Profile>

<Profile/>我有一块 state 持有 boolean 价值:

const [showFollowers, setShowFollowers] = useState(false)

我正在尝试将这块 state 的漏斗连接到我的所有组件。 在我的<Profile/>中,我有这两个功能。

  const handleShowFollowers = () => setShowFollowers(true)
  const handleHideFollowers = () => setShowFollowers(false)

  console.log('from profile', showFollowers) // logs true, then logs false

在简介中

{showFollowers ? <FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} /> : null}

追随者和追随者

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>
  )
}

覆盖

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>
  )
}

当我从我的<Profile/>组件触发handleShowFollowers时,我看到所有三个组件的showFollowers为真。

但是,当我从<FollowersAndFollowing/>组件触发handleHideFollowers时,我看到showFollowers在父组件(配置文件)中翻转为 false,但在其他两个组件中都没有。 是什么原因造成的?

这一行是问题所在:

{showFollowers ? <FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} /> : null}

如果showFollowers为 false,那么您的FollowersAndFollowing组件将根本不会呈现,这就是console.log不记录的原因。

如果你把它改成这样:

<FollowersAndFollowing showFollowers={showFollowers} handleHideFollowers={handleHideFollowers} />

然后,您可以在子组件内部更深地处理隐藏元素,它应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM