[英]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.