[英]How do you throttle a static method in ReactJS?
我正在嘗試編寫 Nylas N1 插件,所以我從修改內置拼寫檢查開始(這里是https://github.com/nylas/N1/blob/master/internal_packages/composer-spellcheck/lib/spellcheck- composer-extension.es6 )。 我導入了下划線庫,並嘗試限制 _wrapMisspelledWords 函數:
import _ from 'underscore';
...
export default class SpellcheckComposerExtension extends ComposerExtension {
...
static onContentChanged({editor}) {
SpellcheckComposerExtension.update(editor);
}
static update = (editor) => {
SpellcheckComposerExtension._unwrapWords(editor);
SpellcheckComposerExtension._wrapMisspelledWords(editor);
}
static _wrapMisspelledWords = _.throttle((editor) => {
console.log('wrap mispelled words');
...
...
}, 2000)
...
}
它起初似乎節流正確,然后似乎卡在某個循環中,不斷重復先前更改的輸出。 我已經閱讀了另一個線程( 在 React.js 中執行去抖動),但無法弄清楚為什么會發生這種行為。
編輯:
限制更新功能可能更有意義,但我看到了同樣的問題。
編輯:
好的,而不是限制或去抖動,我決定將更新函數包裝在 setTimeout(..., 0) 中以進行調試,並且仍然顯示相同的問題。
進入無限循環的條件似乎是:
contenteditable 組件( https://github.com/nylas/N1/blob/1b4739335f4452faa720914309c5e6a593db531d/src/components/contenteditable/contenteditable.cjsx#L302-L333 )有一個突變觀察者,當我認為擴展程序停止監聽時,它會停止監聽我將我的更新添加到事件隊列中,它在更新可以運行之前開始偵聽突變,導致觀察到另一個突變,進入無限循環。
任何解決方案或提示?
我知道這有點晚了,但我以前做過同樣的事情。
class Thing {
static someFn() {
// whatever you do
}
static heavyAJAX() {
// some heavy ajax
}
}
Thing.someFn = _.throttle(Thing.someFn, 2000);
Thing.heavyAJAX = _.debounce(Thing.heavyAJAX, 1000);
這種模式對我debounce
throttle
和debounce
。 您也可以對實例方法使用相同的方法。 如果我們的方法不是static
,您只需使用Thing.prototype
:
Thing.prototype.someFn = _.throttle(Thing.prototype.someFn, 2000);
Thing.prototype.heavyAJAX = _.debounce(Thing.prototype.heavyAJAX, 1000);
如果您要使用實例方法執行此操作,我建議在構造函數中采用一種鎮定方法:
class Thing {
constructor() {
this.someFn = _.throttle(this.someFn, 2000);
}
someFn() {
// your things...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.