то, что я ищу, довольно просто, но я застрял на нем некоторое время:
Я использовал функцию debounce в lodash, чтобы реализовать функцию поиска по мере ввода.
Как правило, когда вы что-то вводите в строке поиска, веб-сайт будет ждать 500 мс после последнего ввода с клавиатуры, прежде чем запускать поиск.
Дело в том, что самый первый вызов не отменяется, так как debounce будет ожидать второго вызова, чтобы ввести задержку.
Прямо сейчас я настроил его с параметрами { trailing: true, leading: false }
, но я не могу понять, как настроить его для первого вызова функции, подлежащего обсуждению.
const DebouncedSearchBox = ({ currentRefinement, refine }) => {
const debouncedSearch = debounce(
e => {
refine(e.target.value);
if (!e.target.value.length) {
document.getElementsByClassName("ais-Pagination-list")
? Array.from(
document.getElementsByClassName("ais-Pagination-list")
).forEach(function(element) {
element.classList.add("hidden");
})
: null;
document.getElementsByClassName("ais-Stats-text")
? Array.from(
document.getElementsByClassName("ais-Stats-text")
).forEach(function(element) {
element.classList.add("hidden");
})
: null;
} else {
document.getElementsByClassName("ais-Pagination-list")
? Array.from(
document.getElementsByClassName("ais-Pagination-list")
).forEach(function(element) {
element.classList.remove("hidden");
})
: null;
document.getElementsByClassName("ais-Stats-text")
? Array.from(
document.getElementsByClassName("ais-Stats-text")
).forEach(function(element) {
element.classList.remove("hidden");
})
: null;
}
document.getElementsByClassName("search_results")
? Array.from(
document.getElementsByClassName("search_results")
).forEach(function(element) {
element.classList.remove("loading");
})
: null;
},
500,
{ trailing: true, leading: false }
);
const onChange = e => {
e.persist();
console.log("on change" + e.target.value);
document.getElementsByClassName("search_results")
? Array.from(
document.getElementsByClassName("search_results")
).forEach(function(element) {
element.classList.add("loading");
})
: null;
debouncedSearch(e);
};
return (
<input
defaultValue={currentRefinement}
onChange={onChange}
aria-label="recherche"
className="ais-SearchBox-input"
autoFocus
onFocus={e => {
let val = e.target.value;
e.target.value = "";
e.target.value = val;
}}
/>
);
};