为什么 setMouseDown(false) 不能互锁回调函数?



如何在fastCount()中使用鼠标向下=真

我不确定 setState 是如何在 React-hooks 中更新的。

鼠标按下状态不会在快速计数函数中更新。

function action(fastCount){
setMouseDown(true);
setTimeout(()=> fastCount(),2000);
}


const fastCount = ()  =>{
console.log(`fastCount에서 실행 : ${mouseDown}`);
if(mouseDown){
setInterval(()=>
{
setNumber(number => number+1)
console.log(`fastCount실행됨`)}, 100);
}


}

return (  
<>
<div>{number}</div>
<button onMouseDown={()=>action(fastCount)}  onMouseUp={plus}>+</button>
<button onMouseDown={minus}>-</button>
</>
);
}

原因是 react 中的状态更新是异步的。您可以自行更新mouseDown,并使用钩子(例如useEffect(检测mouseDown更改。

最新更新