繁体   English   中英

我如何通过RxJS限制对React组件方法的调用

[英]How can I throttle calls of methods of a react component via RxJS

我有以下TSX代码:

public render() {    
  return (
    <div onWheel={this.onWheel}>
      {children}
    </div>
  );
}

private onWheel(event: React.SyntheticEvent<HTMLDivElement>) {...}

我想限制使用RxJS的 this.onWheel调用,以防止频繁的方法调用。

我怎样才能做到这一点?

直接的解决方案是使用Subject:

  • 创建主题并通过节制组件订阅来订阅它
  • 在每个事件上调用其“ next”方法
  • 取消订阅组件卸载

带有删除的TS符号的代码:

render() {    
  return (
    <div onWheel={e => this.onWheel$.next(e)}>
      {children}
    </div>
  );
}

componentWillMount() {
    this.onWheel$ = new Rx.Subject();
    this.onWheel$.throttleTime(500).subscribe(this.onWheel);
}

componentWillUnmount() {
    this.onWheel$.unsubscribe();
}

onWheel(event) {...}

有关工作示例,请参见此jsfiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM