简体   繁体   中英

getting error : Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'

i am new in typescript,i am getting error when i tried to use useEffect in typescript in react, Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'. , can anyone please help me why i am getting this error? here i have put my code, any help will be really appreciated,

const useIsMounted = () => {
        const isMounted = React.useRef(false);
        React.useEffect(() => {
          isMounted.current = true;
          return () => isMounted.current = false;
        }, []);
        return isMounted;
    };

The function of useEffect ( EffectCallback type) should return void or () => void | undefined () => void | undefined .

function useEffect(effect: EffectCallback, deps?: DependencyList): void;

type EffectCallback = () => (void | (() => void | undefined));

In your case, you returning void => boolean :

// void => boolean
return () => (isMounted.current = false);

To fix it, add scope to the statement of the cleaning function:

const useIsMounted = () => {
  const isMounted = React.useRef(false);
  React.useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);
  return isMounted;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM