简体   繁体   English

自定义钩子不会从上下文中获取更新的值

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

I'm trying to use a custom hook to call a function which will be used for multiple components and for a context.我正在尝试使用自定义挂钩来调用 function ,它将用于多个组件和上下文。 However, the hook never gets the context value updated, it is always an empty array, but in the context the state used as the context value gets updated and in the components the context value is received.但是,钩子永远不会更新上下文值,它始终是一个空数组,但在上下文中,用作上下文值的 state 被更新,并且在组件中接收到上下文值。 What is happening in here?这里发生了什么?

It seems to me that the context value is not being passed to the hook, but I don't get why.在我看来,上下文值没有被传递给钩子,但我不明白为什么。

Here is a sample of my code:这是我的代码示例:

Context:语境:

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

Hook:钩:

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;

Component:零件:

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

Is there some kind of limitation when using custom hooks with context or did I miss something?使用带有上下文的自定义钩子时是否有某种限制,或者我错过了什么?

So the context can only be used in descendants of the provider, not inside your provider.所以上下文只能在提供者的后代中使用,而不是在你的提供者内部。 So you should remove it from the provider and use it anywhere that has the Provider wrapped.因此,您应该将其从提供程序中删除,并在包装了提供程序的任何地方使用它。 Also, it is good to make a custom hook with your context and export it from the same Provider file.此外,最好使用您的上下文制作自定义挂钩并将其从同一个 Provider 文件中导出。 Something like this:像这样的东西:

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