这是我的古怪的去盎司函数:
// prevents our function from being repeatedly called
function weirdDebounce(f, wait) {
let timeout = null;
return function() {
let ctx = this,
args = arguments,
callIt = !timeout;
clearTimeout(timeout);
// prevent the function from being called again until
// the timeout has finished
timeout = setTimeout(function() {
timeout = null;
}, wait);
// call the function immediately
if (callIt) f.apply(ctx, args);
};
}
我这样使用它,它被称为inside app.jsx:
function App ({ store }) {
const history = useHistory();
let someClassVariable = useMemo(() => new SomeClass(store, history),[store, history]);
window.testFunction = weirdDebounce(function(param1, param2, param3 = false) {
someClassVariable.someFunction(param1, param2, history, param3).then(function() {});
}, 2000);
return (// some jsx)
}
export default connect(mapStateToProps)(App)
它在vue中工作,但当我在react中执行此操作并运行同一函数两次时,它会忽略超时并仍运行超时。我尝试将函数 Package 为useeffect,并尝试将其 Package 为usecallback。将其 Package 在usecallback中使其能够侦听超时,但随后事情开始变得草率,不起作用/怪异。
事实上,我比vue有更多的React经验,但我不知道如何解决这个问题,有人吗?。
另外,参数并不重要,只是在react中,当运行window.testfunction两次时,它忽略了2000ms超时。
如果能得到任何帮助,我将不胜感激,谢谢。
编辑:使用UseContent使其侦听超时,但存在一个问题。classvariable根据存储区的不同而变化,并且每次调用此函数时它都会变化,因此这意味着使用useconstant将不好,因为函数不会使用变量的新状态,它将使用旧状态,这会导致某些事情无法工作。
更新:我用一个UsedBounce钩子把它包起来解决了这个问题:
import { useCallback, useRef, useEffect } from "react";
// prevents our function from being repeatedly called
function weirdDebounce(f, wait) {
let timeout = null;
return function() {
let ctx = this,
args = arguments,
callIt = !timeout;
clearTimeout(timeout);
// prevent the function from being called again until
// the timeout has finished
timeout = setTimeout(function() {
timeout = null;
}, wait);
// call the function immediately
if (callIt) f.apply(ctx, args);
};
}
export const useDebounce = (cb, delay) => {
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
weirdDebounce((...args) => cbRef.current(...args), delay),
[delay]
);
};
暂无答案!
目前还没有任何答案,快来回答吧!