簡體   English   中英

自定義鈎子不會從上下文中獲取更新的值

[英]Custom hook doesn't get updated value from context

我正在嘗試使用自定義掛鈎來調用 function ,它將用於多個組件和上下文。 但是,鈎子永遠不會更新上下文值,它始終是一個空數組,但在上下文中,用作上下文值的 state 被更新,並且在組件中接收到上下文值。 這里發生了什么?

在我看來,上下文值沒有被傳遞給鈎子,但我不明白為什么。

這是我的代碼示例:

語境:

import { createContext, useState, useEffect } from "react";
import useTest from "./useTest";

const TestContext = createContext({
  test: [],
  testContextFn: () => {}
});

export const TestProvider = ({ children }) => {
  const [testState, setTestState] = useState([]);

  const { testFn } = useTest();

  const testHandlerHandler = () => {
    const test = 1;
    setTestState((current) => [...current, test]);
    testFn();
  };

  const contextValue = {
    test: testState,
    testContextFn: testHandlerHandler
  };

  useEffect(() => {
    console.log("state: ", testState); // => gets the updated value
  }, [testState]);

  return (
    <TestContext.Provider value={contextValue}>{children}</TestContext.Provider>
  );
};

鈎:

import { useContext } from "react";

import { TestContext } from "./hooks/textContext";

const useTest = () => {
  const testCtx = useContext(TestContext);

  const testFn = () => {
    console.log("testCtx: ", testCtx.test); // => Always an empty array
  };

  return { testFn };
};

export default useTest;

零件:

const App = () => {
  return (
    <TestProvider>
      <ExampleComponent />
    </TestProvider>
  );
};



const ExampleComponent = () => {
  const testCtx = useContext(TestContext);
    
 console.log("testCtx: ", testCtx.test); // => Gets the updated value

  return <div onClick={testCtx.testContextFn}>CLICK HERE</div>;
};

使用帶有上下文的自定義鈎子時是否有某種限制,或者我錯過了什么?

所以上下文只能在提供者的后代中使用,而不是在你的提供者內部。 因此,您應該將其從提供程序中刪除,並在包裝了提供程序的任何地方使用它。 此外,最好使用您的上下文制作自定義掛鈎並將其從同一個 Provider 文件中導出。 像這樣的東西:

export function useTestContext() {
  const context = React.useContext(TestContext)
  if (context === undefined) {
    throw new Error('useTestContext must be used within TestProvider')
  }
  return context
}

暫無
暫無

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

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