gpt4 book ai didi

javascript - 收到错误 : Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'

转载 作者:行者123 更新时间:2023-12-03 06:56:33 30 4
gpt4 key购买 nike

我是 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com