[英]Why does lodash throttle not work within the useWindowSize custom hooks?
我正在嘗試使用帶油門的調整大小事件。 但是,它不起作用。 我嘗試按如下方式調試它:
import {throttle} from 'lodash'
export function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
})
const handleResize = () => {
// handle resize code....
}
const onWindowResize = () => {
console.log('Throttle') // <-- this does print out
throttle(() => {
console.log('bam') // <-- this doesn't print out
}, 100)
}
useEventListener('resize', onWindowResize)
return windowSize
}
從上面的代碼可以看出,在使用lodash
的throttle
函數之前,我一直在嘗試注銷。 它確實會打印出來,但throttle
內部的日志不會打印出來。 任何人都知道為什么這可能以及如何解決這個問題?
您的內聯 function 在每次渲染時都會重新錄制。 只需確保油門 function 在下一次渲染時與 function 相同。 您可以使用 useCallback 掛鈎。
export function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined
});
const someFunction = (e) => {
console.log("bam", e); //
};
const throttleFn = useCallback(throttle(someFunction, 1000), []);
const onWindowResize = (e) => {
console.log("Throttle", e);
throttleFn(e);
};
useEventListener("resize", onWindowResize);
return windowSize;
}
我一直在嘗試解決這個問題,並且類似於以下代碼的東西對我有用:
export function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
})
const handleResize = useCallback(() => {
console.log('handleResize') // It does log this out
// handle the resize...
}, [windowSize])
useEventListener('resize', throttle(handleResize, 4000)) // call it here instead
return windowSize
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.