我有点借用我之前问过的一个问题。但是在下面的代码段中,我希望能够多次单击此按钮,但随后仅触发一次函数。我尝试使用setTimeout
,但该功能在延迟后仍会多次触发。接下来,我尝试了debounce
从lodash,但这只是行为完全相同的是什么setTimeout
我错过了一些东西在我的代码?
const handler = debounce(() => {
myFunction(name, age)
}, 1000);
function update() {
handler();
}
<StyledQuantityButton disabled={ amount <= 0 }
onClick={() => {
const newValue = amount - 1;
setAmount(newValue);
update();
}} >
—
</StyledQuantityButton>
虽然您可能已经将myfunction(name, age)
部分放在debounce中,但您的setAmount
部分仍然在debounce之外。
根据你的组件重新渲染的方式,去噪的函数也可能被重新创建(因此失去它的"我刚刚被称为"状态),这将导致同样的问题。试试这个:
const handler = React.useMemo(() => debounce(() => {
setAmount(amount => amount - 1);
myFunction(name, age);
}), [myFunction]);
// ...
onClick={handler}