实际上,我是新手,我试图在输入中加入事件方法( event,onChange),以使代码优化,但是当事件发生时,而不是调用函数一次,它会调用几次(直到无穷大)。
import { useRef } from "react";
import "./styles.css";
export default function App() {
var input_ref = useRef(null)
//.............Debouncing........................................................
var debouncing = (callback,threshold)=>{
var timer;
return function(){
const context = this
if(timer)clearTimeout(timer);
timer = setInterval(()=>{
timer = null;
callback.apply(context);
//callback()
},threshold);
}
}
//........EventHandler with Debouncing............................................
var search_data = debouncing(()=>{
console.log(input_ref.current.value)
},300)
return (
<div className="App">
<input type="text" name='searchBox' placeholder="search" ref={input_ref} onChange={search_data}/>
</div>
);
}链接(CodeSandbox):- https://codesandbox.io/s/debouncing-testing-gxc031?file=/src/App.js
发布于 2022-06-20 05:54:54
哈哈伙计,你的代码工作正常,只是有点粗心大意:它应该是setTimeout,而不是第14行 :P的setInterval。
发布于 2022-06-20 05:59:03
首先,您使用setInterval而不是setTimeout。第二,doesn函数不能正常工作,我只是为您重写了它,并且最好将它移到组件函数之外,请检查下面的代码,它可以根据需要工作。
https://stackoverflow.com/questions/72682694
复制相似问题