防止页面刷新/重新加载-ReactJS

时间:2020-09-27 13:27:03

标签: javascript reactjs

我已经使用React钩子建立了一个倒数计数器,但是当我将它的准确度与它的原始JS对应物进行比较时(我在文档标题上显示了它们的当前计时器,即我在第三个选项卡上处于活动状态),注意到react计时器在一段时间后停止,并且当我打开选项卡时,页面刷新并且计时器重置为其初始状态,而在普通JS版本中没有/没有发生。我想提到的是,我打开了15部YouTube视频,因为我希望计时器在我的机器上进行繁重的工作时能正常工作。如何防止这种情况发生?

这是代码

App.js

import React, { useState } from 'react';
import convertTime from '../helper-functions/convertTime';
import useInterval from '../hooks/useInterval';

const Countdown = () => {
  const [count, setCount] = useState(82.5 * 60);
  const [delay, setDelay] = useState(1000);
  const [isPlaying, setIsPlaying] = useState(false);
  document.title = convertTime(count);
  useInterval(() => setCount(count - 1), isPlaying ? delay : null);

  const handlePlayClick = () => setIsPlaying(true);
  const handlePauseClick = () => setIsPlaying(false);

  const handleResetClick = () => {
    setCount(82.5 * 60);
    setDelay(1000);
    setIsPlaying(false);
  };
  return (
    <div className='counter'>
      <div className='time'>{convertTime(count)}</div>
      <div className='actions'>
        <button onClick={handlePlayClick}>play</button>
        <button onClick={handlePauseClick}>pause</button>
        <button onClick={handleResetClick}>reset</button>
      </div>
    </div>
  );
};

export default Countdown;

useInterval.js

import React, { useState, useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]);
}

export default useInterval;

0 个答案:

没有答案