我有一个带有 React
函数 component
的简单点击事件,我尝试使用 RxJS
throttleTime
进行 throttle 。每次单击我都会在 500 毫秒
内 throttle
,但似乎 throttle 器根本不起作用,但当我使用 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>
);
}
问题是每次点击 clickCount
和 throttleCount
同时增加,但 debounceCount
按预期工作,等待 500ms
和更新。
最佳答案
组件函数 Button()
会在每次状态更改时调用,因此您需要对每次状态更改进行新订阅。这就是为什么它看起来不起作用的原因。
相反,订阅应该进入 useEffect()
:
useEffect(() => {
subject.pipe(throttleTime(400)).subscribe(d => updateThrottled(d));
}, []);
另见 How to call loading function with React useEffect only once .
关于javascript - RXJS - throttle 时间不 throttle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57344194/