React ConstomHook防抖函数应用
js的防抖函数是这样的
function debounce(fn, delay) {
var timer = null;
return function () {
if (timer) clearTimeout(timer);
var _this = this;
var _arguments = arguments;
timer = setTimeout(function () {
// 在执行时,通过apply来使用_this和_arguments
fn.apply(_this, _arguments);
}, delay);
}
}
//使用
document.getElementById('txt').oninput = debounce(function(){
console.log(document.getElementById('txt').value)
setTimeout(()=>{
console.log('timer');
},2000)
},1000)
那么在react当中如何将其抽取成consutom hook 复用呢?
/**
* 防抖函数
*/
export const useDeboundce = (value, delay) => {
const [debouncedBalue, setDebouncedBalue] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebouncedBalue(value), delay);
// 清理上一次的定时器
return () => clearTimeout(timeout);
}, [value, delay]);
return debouncedBalue;
};
//使用
const debouncedParam = useDeboundce(param, 200);
useEffect(() => {
fetch(`xxxx`).then(
async (response) => {
//result...
}
);
//依赖项为useDeboundce hook返回值。
}, [debouncedParam]);
学会了吗?