我是React的新手,因此,作为学习的一部分,我试图在输入框(搜索框模拟)中键入时执行js反跳功能。但是由于某种原因,它不起作用。每次调用该函数都会导致调用超过2000 ms或超时中指定的延迟。以下是沙盒代码的链接,供您参考。我在各个博客中都提到过,实现似乎相同,但我不知道是什么问题。
https://codesandbox.io/s/react-debouncing-9g7tc?file=/src/search.component.js
答案 0 :(得分:0)
问题:
const debounce = (func, delay) => {
let t; // <-- this will be new variable each time function get called
return function() {
clearTimeout(t); // <--- this also points to the new one, so it will clear nothing
// so all the previously called func will be called
t = setTimeout(() => func(), delay);
};
};
第一个解决方案:useRef
const t = useRef(null);
const debounce = (func, delay) => {
return function() {
clearTimeout(t.current); // <--- pointing to prev setTimeout or null
t.current = setTimeout(() => func(), delay);
};
};
工作演示
第二个解决方案:在t
的范围之外定义SearchUi
var t;
const SearchUi = () => {
...
const debounce = (func, delay) => {
return function() {
clearTimeout(t);
t = setTimeout(() => func(), delay);
};
};
...
};
工作演示