zoukankan      html  css  js  c++  java
  • React hooks使用 setInterval

    // 自定义 useInterval Hook
    import React, { useState, useEffect, useRef } from 'react';
    
    export function useInterval(callback, delay) {
      const savedCallback = useRef();
    
      // Remember the latest callback.
      useEffect(() => {
        savedCallback.current = callback;
      });
    
      // Set up the interval.
      useEffect(() => {
        function tick() {
          savedCallback.current();
        }
        if (delay !== null) {
          let id = setInterval(tick, delay);
          return () => clearInterval(id);
        }
      }, [delay]);
    }
    

    使用:

    import React, { useState, useEffect, useRef } from 'react';
    
    function Counter() {
      let [count, setCount] = useState(0);
    
      useInterval(() => {
        // Your custom logic here
        setCount(count + 1);
      }, 1000);
    
      return <h1>{count}</h1>;
    }
    

      摘自原文:https://segmentfault.com/a/1190000018224631

      

  • 相关阅读:
    iBatis,第二次亲密接触
    微斯人,吾谁与归
    一个月了
    生命在于运动
    眼皮跳了好几天
    往返
    中病毒,学习批处理

    爱如潮水
    今天夏至
  • 原文地址:https://www.cnblogs.com/peter-web/p/15245665.html
Copyright © 2011-2022 走看看