取消功能不起作用-REACT功能组件

我是React的新手,因此作为学习的一部分,我尝试在输入框(搜索框模拟)中键入时执行js反跳功能。但是由于某种原因,它不起作用。每次调用该函数都会导致调用超过2000 ms或超时中指定的延迟。以下是沙盒代码的链接,供您参考。我在各个博客中都提到过,实现似乎相同,但我不知道是什么问题。

https://codesandbox.io/s/react-debouncing-9g7tc?file=/src/search.component.js

评论
侵蚀内心
侵蚀内心

问题 :

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);
    };
};

工作演示

Edit react-debouncing-solved

2nd Solution : Define t outside scope of SearchUi

var t;
const SearchUi = () => {
    ...

    const debounce = (func, delay) => {
        return function() {
            clearTimeout(t);
            t = setTimeout(() => func(), delay);
        };
    };

    ...
};

工作演示

Edit react-debouncing-solved2

点赞
评论