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