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

      

  • 相关阅读:
    CSS
    表单
    框架
    表格
    列表
    定位--position属性
    浮动
    选择结构
    数组
    TextView(标签控件)
  • 原文地址:https://www.cnblogs.com/peter-web/p/15245665.html
Copyright © 2011-2022 走看看