React + TypeScript:setInterval() 示例

这篇实用的文章将引导您完成一个完整的示例,该示例在使用TypeScript 编写的 React 应用程序中结合使用window.setInterval()方法和钩子( useStateuseEffectuseRef)。

简要概述

setInterval() 方法用于以指定的时间间隔(以毫秒为单位)调用给定的函数。使用 TypeScript 为在 Web 浏览器中运行的前端应用程序编写代码时,间隔的正确类型是数字, 并且应该使用window.setInterval()显式调用 setInterval() 方法,如下所示:

let myInterval: number;

// setInterval
myInterval = window.setInterval(() => {/* ...*/}, 1000);

// clearInterval
window.clearInterval(myInterval);

在 React 中,您可以将setInterval() 与useRefuseStateuseEffect钩子一起使用,如下所示:

const intervalref = useRef<number | null>(null);

// Start the interval
const startInterval = () => {
    if (intervalref.current !== null) return;
    intervalref.current = window.setInterval(() => {
      /* ...*/
    }, 1000);
};

// Stop the interval
const stopInterval = () => {
    if (intervalref.current) {
      window.clearInterval(intervalref.current);
      intervalref.current = null;
    }
};

// Use the useEffect hook to cleanup the interval when the component unmounts
useEffect(() => {
    // here's the cleanup function
    return () => {
      if (intervalref.current !== null) {
        window.clearInterval(intervalref.current);
      }
    };
}, []);

这种解释可能看起来含糊不清。请参阅下面的完整工作示例以获得更清晰的信息。

这个例子

应用预览

我们要构建的示例演示是一种计数器 Web 应用程序。它有 2 个按钮:

  • 开始:按下此按钮时,计数器每秒增加 1 个单位。此外,此按钮也将被禁用。
  • 停止和复位:当计数器不运行时,此按钮被禁用。当计数器开始运行时,此按钮是可按下的。当它被按下时,计数器将停止并重置为 0。当计数器不运行时禁用此按钮是有意义的。

下面的动画 GIF 屏幕截图清楚地描述了您将在一天结束时完成的工作:

React + TypeScript:setInterval() 示例

代码

  1. 为确保我们在同一时间开始编写代码,使用 TypeScript 初始化一个全新的 React 项目:
npx create-react-app kindacode-example --template typescript

这个名字完全取决于你。从现在开始,我们只关心 2 个文件:src/App.tsxsrc/App.css

  1. 这里是src/App.tsx的完整源代码(在评论中有解释):
// Kindacode.com
// App.tsx
import React, { useState, useRef, useEffect } from 'react';
import './App.css';

const App = () => {
  // Count state
  // This will be displayed in the UI
  const [count, setCount] = useState(0);

  // Ref
  // This will be used to store the interval
  const intervalref = useRef<number | null>(null);

  // Start the interval
  // This will be called when the user clicks on the start button
  const startInterval = () => {
    if (intervalref.current !== null) return;
    intervalref.current = window.setInterval(() => {
      setCount((prevCount) => prevCount + 1);
    }, 1000);
  };

  // Stop the interval
  // This will be called when the user clicks on the stop button
  const stopInterval = () => {
    if (intervalref.current) {
      window.clearInterval(intervalref.current);
      setCount(0);
      intervalref.current = null;
    }
  };

  // Use the useEffect hook to cleanup the interval when the component unmounts
  useEffect(() => {
    // here's the cleanup function
    return () => {
      if (intervalref.current !== null) {
        window.clearInterval(intervalref.current);
      }
    };
  }, []);

  return (
    <div className='container'>
      {/* Render Count */}
      <h1 className='count'>{count}</h1>

      {/* Start & Stop buttons */}
      <div className='buttons'>
        <button
          // Disable the button if the interval is running
          disabled={intervalref.current !== null}
          onClick={startInterval}
          className='start-button'
        >
          Start
        </button>
        <button
          // Disable the button if the interval is not running
          disabled={intervalref.current === null}
          onClick={stopInterval}
          className='stop-button'
        >
          Stop and Reset
        </button>
      </div>
    </div>
  );
};

export default App;

3. 使用以下内容删除App.css中的所有默认代码:

/* App.css */
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* Style the "count" number */
.count {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: #ffc107;
  font-size: 100px;
}

/* The parent div of the two buttons */
.buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* Start Button */
.start-button {
  background-color: #2196f3;
  border: none;
  color: white;
  width: 200px;
  padding: 15px 32px;
  margin: 4px 2px;
  cursor: pointer;
}

.start-button:hover {
  background-color: #0b7dda;
}

.start-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* Stop Button */
.stop-button {
  background-color: #f44336;
  border: none;
  color: white;
  width: 200px;
  padding: 15px 32px;
  margin: 4px 2px;
  cursor: pointer;
}

.stop-button:hover {
  background-color: #da190b;
}

.stop-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

4.通过执行以下命令启动它:

npm start

最后,前往 http://localhost:3000 查看结果。

结论

您已经学习了如何在使用TypeScript 实现的 React 项目中使用带有钩子的setInterval()函数。 有了这些知识,你以后可以开发更复杂更复杂的东西。