令我惊讶的是,下面的代码旨在限制我的 React Component 类中的 mousemove
并没有按预期工作,状态始终报告为 true 并且 mousemove 继续连续触发。我不明白为什么会这样。
class SVGParent extends React.Component {
constructor(){
super( props );
...
this.dispatchMouseMoveThrottle = this.dispatchMouseMoveThrottle.bind( this );
}
...
dispatchMouseMoveThrottle( a ){
let state = true;
let dispatchMouseMove = this.props.dispatchMouseMove;
return( function( e ){
e.persist(); // this excludes from React's synthetic event system
setTimeout( function(){
state = true;
}, 5000);
if( state === true ){
state = false;
return( dispatchMouseMove( abc ));
}
});
}
render(){
...
return(
<svg
...
mousemove = {this.dispatchMouseMoveThrottle( a )}
</svg>
);
}
最佳答案
我认为,问题是当 mousemove
事件触发时,它不会调用 dispatchMouseMoveThrottle(a)
返回的函数。相反,它会在每次触发时调用 dispatchMouseMoveThrottle(a)
。这就是为什么 state
变量始终为 true
。
我认为你最好将 state
变量保留为组件中的全局变量。或者您可以尝试使用 lodash
debounce
或 throttle
方法,这可能会有所帮助。
关于javascript - React 中的 throttle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43687551/