useState设置时间导致定时器失效

新手上路,请多包涵
我是一个react的初学者。在学习React时,我实现了一个对点击事件节流的demo。设置定时器每2s触发一次,但是当我把值设置为常数时,程序可以正常运转,但是当我把值设置为useState时,程序的debounce节流函数,表现得就像失效了一样,我不太理解原因是什么,希望有路过的大佬帮忙解答一下。
import { useRef, useState } from 'react';

function But(props) {
  const { count, setCount } = props;
  const timer = useRef(null);
  // const time = useState(2000);  这样写debounce函数失效
  const time = 2000;  // 这样写就没有问题
  const debounce = function (cb, time) {
    return function () {
      if (!timer.current) {
        cb();
        timer.current = setTimeout(() => {
          clearTimeout(timer);
          timer.current = null;
        }, time);
      }
    };
  };
  const handleClick = debounce(() => {
    setCount({ ...count, count: count.count + 1 }); 
  },time);
  return (
    <>
      <div onClick={handleClick}>增加</div>
      {count.count}
    </>
  );
}

export default But;

这是父组件

import { useState } from 'react';
import But from './But';

function Counter() {
  const [count, setCount] = useState({ count: 0 });
  return (
    <>
      <But count={count} setCount={setCount}></But>
    </>
  );
}

export default Counter;
阅读 1.5k
1 个回答

失效是因为useState返回的是[T,React.Dispatch<React.SetStateAction<T>>]形式的元组,如果想把time变为组件的状态,那应该这样写:
const [time,setTime] = useState(2000);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题