[英]How to not fire throttle function from lodash?
我在我的 React 項目中有一個來自 lodash 的節流閥 function。 如果參數value
的長度為零,則不應執行 function。
任何人都可以幫我嗎? 我已經開始檢查值的長度並說throttling(false)
但這不起作用。
const throttling = useCallback(
throttle(function(value) {
if (value.length > 0) {
const myFetch = fetch(fetchApi + encodeURIComponent(value))
myFetch.then(response => response.json()).then(setSearchResult)
} else {
console.log('0')
}
}, 500),
[]
)
function handleChange(event) {
throttling(event.target.value)
onChange(event.target.value)
}
你為什么不反過來go?
function handleChange(event) {
if (event.target.value.length > 0) {
throttling(event.target.value)
}
onChange(event.target.value)
}
這樣 function 僅在值高於 0 時觸發,否則不執行任何操作。
編輯:如果您想始終觸發 function,這將是另一種方法:
const throttling = (value) => {
const myFetch = fetch(
"http://localhost:8000/api/auto-suggest?input=" +
encodeURIComponent(value)
);
useCallback(
value.length > 0
? myFetch.then(response => response.json()).then(setSearchResult)
: throttle(function(value) {
myFetch.then(response => response.json()).then(setSearchResult);
}, 500),
[]
);
};
function handleChange(event) {
throttling(event.target.value);
onChange(event.target.value);
}
檢查現在在使用回調 function 中,如果值的長度大於 0,將使用throttle
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.