如何在 Gatsby Js 项目中管理状态

How to manage state in Gatsby Js project

我已经在 Gatsby js 中设置了我的项目。在头文件中,我在单击 header.js 文件中的按钮时为切换按钮创建了一个状态。我需要在我的页面中使用该按钮状态,所以我怎样才能从页眉中获取该状态到我的页面中(比如在关于我们的页面中)。

您有多种方法可以做到这一点,从使用上下文 (useContext hook) 到最直接的方法(提升状态的值)。

没有任何其他实施细节,我会选择第二个。

const Header = ({ sendStateToParent: {} }) => {
   const [isOpen, setIsOpen] = useState(false);

   const handleOnClick=()=>{
     setIsOpen(!isOpen);
     sendStateToParent(isOpen);
   }

   return <section>
      Some Header stuff
      <div onClick={handleOnClick}>I'm a hamburger menu</div>
   </section
}

注意:我正在解构 props,但如果需要,您可以使用 props.sendStateToParent

基本上,您是通过 props 发送一个函数(sendStateToParent,设置为空对象以避免代码中断,如果它不是从 Header 所在的所有页面收到的使用过,但您也可以将其设置为 void 函数)。 onClick 函数处理内部状态 (isOpen),切换其值,并通过 sendStateToParent(来自 props)提升当前值。

因此,您的父组件 (about.js) 应如下所示:

const About=()=>{
  const sendStateToParent = (isOpen) =>{
    console.log("The menu is:", isOpen)
  }

  return <Layout>
   <Header sendStateToParent={sendStateToParent} />
   <h2>Some other content </h2>
  <Layout>
}

在父组件(About)中必须定义发送给子组件(Header)的函数,sendStateToParent接收一个值(isOpen ) 因为子组件中的 handleOnClick

所以在你的 sendStateToParent 中你可以获得 isOpen 的当前状态,在那里你可以随心所欲地播放它(在 useEffect 钩子中使用它,等等).