【发布时间】:2019-10-22 16:41:48
【问题描述】:
我有:
一个自定义的钩子,基本上是useContext(MyContextName);。
一个组件Container,它接收孩子并将它们包装在我的上下文提供程序中并将我的函数传递给那里;
我想在其中使用我的功能的组件。我正在从自定义钩子中解构它并尝试在useEffect 中调用它。
我不能包含代码,但这里是简化版:
const MyContext = createContext({});
export const MyContainer = ({children}) => {
const MyCoolFunction = async() =>{
//do something
}
return (
<MyContext.Provider value={{
MyCoolFunction
}}>
{children}
</MyContext.Provider>
)
}
export const useMyHook = () => useContext(MyContext);
在另一个组件中我会这样做
const MyComponent = () => {
const {MyCoolFunction} = useMyHook();
useEffect(() => {
MyCoolFunction();
}, []);
return <something />;
}
在调用MyCoolFunction 的那一刻,我收到“无效的挂钩调用”错误。但是MyCoolFunction 不是一个钩子,是吗?我究竟做错了什么 ?
【问题讨论】:
-
codesandbox.io/embed/new?fontsize=14这里没有错。问题是你在哪里打电话给
useMyHook? -
@Dupocas,不,我检查了这个。它不起作用,但出于其他一些原因。我现在只需要处理这个无效的钩子调用来修复其余的功能
-
发布一个包含更多细节的沙盒
标签: reactjs react-hooks react-context