在这种情况下如何清除超时?

how can I clear the timeout in this case?

在这种情况下如何清除超时?

代码:

  const [flag, setFlag] = useState<boolean>(false);

  const timerFlag = useRef<null | ReturnType<typeof setTimeout>>(null);

  const handlePressCancel2 = () => {
     timerFlag.current = setTimeout(() => {
     setFlag(true)
    }, 150);
  }

尝试做一个return清除时间 return () => clearTimeout(handlePressCancel2)

如果您想在销毁组件时清除超时,您必须为此使用 useEffect

 const [flag, setFlag] = useState<boolean>(false);

 const timerFlag = useRef<null | ReturnType<typeof setTimeout>>(null);

 const handlePressCancel2 = () => {
    timerFlag.current = setTimeout(() => {
      setFlag(true);
    }, 150);
  };

 useEffect(() => {
    return () => {
      if (timerFlag.current) {
        clearTimeout(timerFlag.current);
      }
    };
 }, []);