我是 typescript 的新手,当我尝试使用 useEffect
时出现错误在 typescript 中 react ,Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'.
,任何人都可以帮助我为什么会收到这个错误?我在这里放了我的代码,任何帮助将不胜感激,
const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
return isMounted;
};
最佳答案
useEffect
的功能( EffectCallback
类型)应该返回 void
或 () => void | undefined
.
function useEffect(effect: EffectCallback, deps?: DependencyList): void;
type EffectCallback = () => (void | (() => void | undefined));
在您的情况下,您返回 void => boolean
:// void => boolean
return () => (isMounted.current = false);
要修复它,请将范围添加到清理函数的语句中:const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return isMounted;
};
关于javascript - 收到错误 : Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62794003/