[英]How to dispatch an action with delay (debounce)
我有一個場景,我需要在輸入完成兩秒后調度一個動作。 (假設用戶輸入 1000 沒有 2 秒的間隔,所以我需要在輸入 1000 並在 2 秒后發送操作)。
以前我使用debounce-promise來做這樣的事情,我需要從 API 獲取下拉列表,但為此我直接使用了帶有 AJAX 調用的庫組件。 它工作正常。
現在我需要發送這樣的動作。
// should be dispatched only for the last request
const getRateReq = dispatch(getRates());
const getRate = debounce(getRateReq, 2000, {
leading: false,
});
const onChange = (e) => {
setValue(e.target.value);
getRate(e.target.value);
}
現在,該動作也僅在完成輸入兩秒后才調度。 但隨后它會發出 1、10、100、1000 的所有請求(即使在沒有兩秒間隔的情況下輸入 1000)。 如何修復此問題並僅在 2 秒內為最后一個輸入調度一個動作?
任何幫助,將不勝感激。 謝謝
編輯:添加了基本的 onChange function
你可以做這樣的事情。
let timeOut = null;
SearchFilter: (name, value) => {
clearTimeout(timeOut);
dispatch(SearchFilter(name, value));
timeOut = setTimeout(() => {
dispatch(callfunction());
}, 2000);
}
它將調度等待輸入 2 秒的操作。
您需要使用 loadash 的 debounce 方法並執行以下操作:
onChange = debounce(anyInput => {
}, 2000);
因此,您必須在完成輸入后 2 秒后在 onchange 方法中調用 API 。 不確定這是您要問的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.