反应中的节流

时间:2017-04-28 19:24:48

标签: javascript class reactjs events mouseevent

令我惊讶的是,以下代码,意味着在我的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>
        );
}

2 个答案:

答案 0 :(得分:1)

我认为,问题是当mousemove事件触发时,它不会调用dispatchMouseMoveThrottle(a)返回的函数。相反,它每次触发时都会调用dispatchMouseMoveThrottle(a)。这就是为什么state变量总是true

我认为您最好将state变量保留为组件中的全局变量。或者您可以尝试使用lodash debouncethrottle方法,这可能会有所帮助。

答案 1 :(得分:0)

我通过在模块和模块中声明global变量来解决它。然后在组件内读取/修改它。

代码:

let mouseMoveState = true;
const changeMouseMoveState = function( changeTo ){
    mouseMoveState = changeTo;
};

class SVGParent extends React.Component{
 ...
    dispatchMouseMoveThrottle( a, b ){
        let dispatchMouseMove = this.props.dispatchMouseMove;
        return( function( e ){
            if( a.mouseDownState === true ){
                e.persist(); // this excludes from React's synthetic event system
                if( mouseMoveState === true ){
                    setTimeout( function(){
                        changeMouseMoveState( true );
                    }, 500 );
                    changeMouseMoveState( false );
                    return( dispatchMouseMove( a, b ));
                }

            }
        });
    }