簡體   English   中英

在 IIFE 中使用 React Hook 打破了鈎子的規則

[英]Using React Hooks in in an IIFE breaks rules of hooks

背景

我正在開發一個可以從 UI 中的許多按鈕打開的側邊欄組件。 我想 1) 只渲染一次,2) 授予訪問權限以更新這些按鈕的isVisible狀態,而無需通過共同的祖先向下鑽取道具。

期望與現實

我希望我可以使用自己的 api 方法創建一個上下文來更新內部狀態。 在我的代碼示例中,我試圖用 IIFE 來做到這一點。

問題

  1. 這如何打破鈎子的規則?
  2. 我還能如何為此上下文提供更新功能?
export const SidebarContext = createContext((() => {
  const [isVisible, setIsVisible] = useState(false)

  return {
    isVisible,
    toggleVisibility: () => setIsVisible(!isVisible)
  }
})())

createContext()接收默認值。 因此,您正在定義一個立即調用的函數,其結果將用作上下文的默認值。 這就是useState打破這條規則的地方

從 React 函數組件調用 Hook。

為了完成你想要的,你可以這樣做:

import React, { createContext, useContext, useState } from "react";

const SidebarContext = createContext();

function Provider({ children }) {

  let [isVisible, setIsVisible] = useState(false);
  let toggle = useCallback(() => setIsVisible(s => !s), [setIsVisible])

  // Pass the `state` and `functions` to the context value
  return (
    <SidebarContext.Provider value={{ isVisible, toggle }}>
      {children}
    </SidebarContext.Provider>
  );
}

function YourButton() {
  let { isVisible, toggle } = useContext(SidebarContext);
  return (
    <div>
      <div>Sidebar is {isVisible : 'open': 'close'}</div>
      <button onClick={toggle}>
        Toggle
      </button>
    </div>
  );
}

function App() {
  return (
    <Provider>
      <YourButton />
    </Provider>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM