美文网首页
react hooks 中的setInterval的应用

react hooks 中的setInterval的应用

作者: 泽赫 | 来源:发表于2020-10-12 16:47 被阅读0次

react hooks 中的setInterval的应用

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function Counter() {
  const [count, setCount] = useState(0);
  const [delay, setDelay] = useState(1000);
  const [isRunning, setIsRunning] = useState(true);

  useInterval(() => {
    // Your custom logic here
    setCount(count + 1);
  }, isRunning ? delay : null);

  function handleDelayChange(e) {
    setDelay(Number(e.target.value));
  }

  function handleIsRunningChange(e) {
    setIsRunning(e.target.checked);
  }

  return (
    <>
      <h1>{count}</h1>
      <input type="checkbox" checked={isRunning} onChange={handleIsRunningChange} /> Running
      <br />
      <input value={delay} onChange={handleDelayChange} />
    </>
  );
}

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

  // Remember the latest function.
  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]);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

相关文章

  • react hooks 中的setInterval的应用

    react hooks 中的setInterval的应用

  • 让setInterval在React-Hooks成为声明式

    Making setInterval Declarative with React Hooks 原文: Makin...

  • React Hooks 精讲

    这篇文章主要介绍 React 新特性 Hooks 以及应用场景。 React Hooks 是 React 的一个新...

  • React Hooks与setInterval

    前言 Hooks出来已经有段时间了,相信大家都用过段时间了,有没有小伙伴们遇到坑呢,我这边就有个setInterv...

  • React hooks(钩子)

    React hooks(钩子) React hooks 是React 16.8中的新增功能。它们使您无需编写类即可...

  • 使用 React Hooks 声明 setInterval

    来自Dan 写的一篇文章:https://overreacted.io/zh-hans/making-setint...

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • React Hooks

    前言 React Conf 2018 上 React 提出了关于 React Hooks 的提案,Hooks 作为...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • react-hooks

    react-hooks react-hooks 是react16.8以后,react新增的钩子API,目的是增加代...

网友评论

      本文标题:react hooks 中的setInterval的应用

      本文链接:https://www.haomeiwen.com/subject/xqhppktx.html