React 上下文值未更新

时间:2021-02-12 16:06:42

标签: reactjs react-context

我试图实现一个导航抽屉。首先,我制作了一个导航抽屉布局,其中包含导航抽屉本身和子项,以及在未显示导航抽屉时出现的其他组件。

index.tsx

  const [active, setActive] = useState(false);

  function drawerActivationToggler() {
    console.log(active); // this logs the changes as expected
    setActive(!active)
  }

  return (
    <>
      <NavDrawerContext.Provider value={{ active: false, toggleActivation: drawerActivationToggler }}>
        <NavigationDrawerLayout active={active} direction="right" drawer={<div>hello</div>} >
          <NavBar></NavBar>
        </NavigationDrawerLayout>
      </NavDrawerContext.Provider>
    </>
  )

nav-bar.tsx

// some code...
<NavDrawerContext.Consumer>
    {
        ({ toggleActivation }) => {
            return (
                <li onClick={toggleActivation}><i className="fas fa-bars"></i></li>
            )
        }
    }
</NavDrawerContext.Consumer>

NavigationDrawerLayou.tsx

<NavDrawerContext.Consumer>
    {
        ({ active, toggleActivation }) => {
            console.log('inside ',active); // always false
            return (
                <div style={{ position: "relative", overflowX: "hidden" }}>
                    <section className={`${styles[`drawer-section-${direction}`]} ${active ? styles["active"] : ""}`}>{drawer}</section>
                    <section onClick={toggleActivation} className={`${styles[`shadow`]} ${active ? styles["active"] : ""}`}></section>
                    {/*children contains the navbar component that toggles activation*/}
                    <section style={{ height: "100vh", overflowY: active ? "hidden" : "scroll" }} className={`${styles[`children-section`]} ${active ? styles["active"] : ""}`}>{children}</section>
                </div>
            )
        }
    }
</NavDrawerContext.Consumer>

切换函数内部的日志本身按预期工作,但是消费者内部的日志总是返回 false。为什么会这样?

1 个答案:

答案 0 :(得分:1)

那是因为您总是在提供程序中传递值 active: false

<NavDrawerContext.Provider value={{ active: false, toggleActivation: drawerActivationToggler }}>
  <NavigationDrawerLayout active={active} direction="right" drawer={<div>hello</div>} >
    <NavBar></NavBar>
  </NavigationDrawerLayout>
</NavDrawerContext.Provider>

应该是:

<NavDrawerContext.Provider value={{ active, toggleActivation: drawerActivationToggler }}>
...