反应如何在useEffect之外清理setTimeout

时间:2020-06-11 06:23:03

标签: reactjs

如果我在useEffect之外使用setTimeout和setState,如何在卸载时对其进行清理?

const MyComponents = () => {
  const [myState, setMyState] = useState(null);

  const handlePress = () => {
    setTimeout(() => {
      setMyState('...');
    }, 1000);
  };

  return <button onPress={handlePress} />;
};

如果我在时间到之前离开页面(例如卸下组件),我会得到

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

1 个答案:

答案 0 :(得分:3)

将超时ID保存在引用中,并用于清除效果:

const MyComponents = () => {
  const [myState, setMyState] = useState(null);

  const idRef = useRef();

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

  const handlePress = () => {
    const id = setTimeout(() => {
      setMyState("...");
    }, 1000);
    idRef.current = id;
  };

  return <button onPress={handlePress} />;
};