[英]Debounce in React component JS
I'm writing a simple debounce function for an input component我正在为输入组件编写一个简单的去抖动 function
export const debounce = (func, wait) => {
let timeout
return function (...args) {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
timeout = null
Reflect.apply(func, this, args)
}, wait)
}
}
it imported from an external file, and used as a wrap for input
onKeyUp handler inside a React component (Hooks)它从外部文件导入,并用作 React 组件(Hooks)中
input
onKeyUp 处理程序的包装
const handleChange = debounce(() => console.log("test"), 1000)
PROBLEM: I'm getting "test" log every time when text in input
changes, not only one - as expected.问题:每次当
input
中的文本发生变化时,我都会收到“测试”日志,而不仅仅是一个 - 正如预期的那样。
What am I doing wrong?我究竟做错了什么?
I'm not sure what is the problem with your code but here is a version with hooks working我不确定您的代码有什么问题,但这是一个可以使用挂钩的版本
import { useEffect, useState } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
and then you use it as然后你用它作为
const debouncedValue = useDebounce(inputValue, delay);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.