如何使用React Hooks在点击时清除Interval?

时间:2018-12-19 21:46:49

标签: reactjs react-hooks

我正在尝试重构代码以响应钩子,但是我不确定自己是否正确执行了操作。我尝试将setInterval / setTimout代码复制并粘贴到挂钩中,但是没有按预期工作。在尝试了不同的方法之后,我能够使其工作,但是我不确定这是否是最好的方法。

我知道我可以使用useEffect清除卸载时的间隔,但是我想在卸载前清除它。

以下做法是否是好的做法?如果不是,那么在卸载之前清除setInterval / setTimout的更好方法是什么?

谢谢

useTimeout

import { useState, useEffect } from 'react';

let timer = null;

const useTimeout = () => {
    const [count, setCount] = useState(0);
    const [timerOn, setTimerOn] = useState(false);

    useEffect(() => {
        if (timerOn) {
            console.log("timerOn ", timerOn);

            timer = setInterval(() => {
                setCount((prev) => prev + 1)
            }, 1000);

        } else {
            console.log("timerOn ", timerOn);
            clearInterval(timer);
            setCount(0);
        }
    return () => {
        clearInterval(timer);
    }
    }, [timerOn])

    return [count, setCount, setTimerOn];
}

export default useTimeout;

组件

import React from 'react';
import useTimeout from './useTimeout';

const UseStateExample = () => {
    const [count, setCount, setTimerOn] = useTimeout()
    return (
        <div>
            <h2>Notes:</h2>
            <p>New function are created on each render</p>
            <br />
            <h2>count = {count}</h2>
            <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
            <br />
            <button onClick={() => setCount(prev => prev - 1)}>Decrement</button>
            <br />
            <button onClick={() => setTimerOn(true)}>Set Interval</button>
            <br />
            <button onClick={() => setTimerOn(false)}>Stop Interval</button>
            <br />

        </div>
    );
}

export default UseStateExample;

2 个答案:

答案 0 :(得分:2)

---添加于@ 2019-02-11 15:58 ---

setInterval与Hooks API结合使用的好模式:

https://overreacted.io/making-setinterval-declarative-with-react-hooks/


---原点答案---

一些问题:

  1. 请勿在任何模块的全局范围内使用非常量变量。如果您在一页中使用此模块的两个实例,它们将共享这些全局变量。

  2. 无需清除“ else”分支中的计时器,因为如果timerOn从true更改为false,则将执行返回功能。

一种更好的想法:

import { useState, useEffect } from 'react';

export default (handler, interval) => {
  const [intervalId, setIntervalId] = useState();
  useEffect(() => {
    const id = setInterval(handler, interval);
    setIntervalId(id);
    return () => clearInterval(id);
  }, []);
  return () => clearInterval(intervalId);
};

此处运行示例:

https://codesandbox.io/embed/52o442wq8l?codemirror=1

答案 1 :(得分:0)

在此示例中,我们添加了几件事...

  1. 用于超时的on / off开关(“运行中的arg”)将完全打开或关闭该开关

  2. 重置功能,允许我们随时将超时设置回零:

    如果在运行时调用,它将继续运行,但返回0。 如果在不运行时调用它,它将启动它。

const useTimeout = (callback, delay, running = true) => {
  // save id in a ref so we make sure we're always clearing the latest timeout
  const timeoutId = useRef('');

  // save callback as a ref so we can update the timeout callback without resetting it
  const savedCallback = useRef();
  useEffect(
    () => {
      savedCallback.current = callback;
    },
    [callback],
  );

  // clear the timeout and start a new one, updating the timeoutId ref
  const reset = useCallback(
    () => {
      clearTimeout(timeoutId.current);

      const id = setTimeout(savedCallback.current, delay);
      timeoutId.current = id;
    },
    [delay],
  );

  // keep the timeout dynamic by resetting it whenever its' deps change
  useEffect(
    () => {
      if (running && delay !== null) {
        reset();

        return () => clearTimeout(timeoutId.current);
      }
    },
    [delay, running, reset],
  );

  return { reset };
};

所以在上面的示例中,我们可以像这样使用它...

const UseStateExample = ({delay}) => {
    // count logic
    const initCount = 0
    const [count, setCount] = useState(initCount)
    
    const incrementCount = () => setCount(prev => prev + 1)
    const decrementCount = () => setCount(prev => prev - 1)
    const resetCount = () => setCount(initCount)

    // timer logic
    const [timerOn, setTimerOn] = useState(false)
    const {reset} = useTimeout(incrementCount, delay, timerOn)

    const startTimer = () => setTimerOn(true)
    const stopTimer = () => setTimerOn(false)
    
    return (
        <div>
            <h2>Notes:</h2>
            <p>New function are created on each render</p>
            <br />
            <h2>count = {count}</h2>
            <button onClick={incrementCount}>Increment</button>
            <br />
            <button onClick={decrementCount}>Decrement</button>
            <br />
            <button onClick={startTimer}>Set Interval</button>
            <br />
            <button onClick={stopTimer}>Stop Interval</button>
            <br />
            <button onClick={reset}>Start Interval Again</button>
            <br />

        </div>
    );
}