【问题标题】:RXJS - throttleTime not throttleRXJS - 节流时间不节流
【发布时间】:2019-12-12 03:03:17
【问题描述】:

我有一个带有React 函数component 的简单点击事件,我尝试使用RxJS throttleTime 进行节流。每次点击我throttle500ms,但似乎油门根本不起作用,但是当我使用 debounce 时它起作用了。

import React, { useState, useRef } from "react";
import { throttleTime, debounceTime } from "rxjs/operators";
import { Subject } from "rxjs";

const subject = new Subject();

function Button() {
  const btn = useRef();
  const [clickCount, updateClick] = useState(0);
  const [debounceCount, updateDebounced] = useState(0);
  const [throttleCount, updateThrottled] = useState(0);
  const onClicked = e => {
    updateClick(parseInt(e.target.value, 10) + 1);
    subject.next(parseInt(e.target.value, 10) + 1);
  };
  subject.pipe(debounceTime(500)).subscribe(d => updateDebounced(d));
  subject.pipe(throttleTime(400)).subscribe(d => updateThrottled(d));
  return (
    <div className="button">
      <button value={clickCount} ref={btn} onClick={onClicked}>
        CLICK
      </button>
      <div>Actual clicks: {clickCount}</div>
      <div>Debounced clicks: {debounceCount}</div>
      <div>Throttle click: {throttleCount}</div>
    </div>
  );
}

问题是每次点击clickCountthrottleCount 都会同时增加,但debounceCount 按预期工作,它等待500ms 和更新。

working live demo

【问题讨论】:

    标签: javascript rxjs throttling debounce


    【解决方案1】:

    组件函数Button() 在每次状态更改时被调用,因此您在每次状态更改时都进行新订阅。这就是为什么它看起来不起作用的原因。

    相反,订阅应该进入useEffect()

    useEffect(() => {
      subject.pipe(throttleTime(400)).subscribe(d => updateThrottled(d));
    }, []);
    

    另见How to call loading function with React useEffect only once

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 2012-12-23
      • 1970-01-01
      • 2020-07-24
      • 2021-11-30
      • 2017-02-02
      • 2011-10-18
      • 2012-01-24
      • 1970-01-01
      相关资源
      最近更新 更多