Estoy tratando de usar el evento de cambio de tamaño con el acelerador. Sin embargo, no funciona. Intenté depurarlo de la siguiente manera:
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 } Como se ve en el código anterior, he estado tratando de cerrar sesión antes de usar la función de throttle de lodash . Se imprime, pero el registro dentro del throttle no lo hace. ¿Alguien sabe por qué esto tal vez y cómo solucionarlo?
Su función en línea recreada en cada renderizado. Solo asegúrese de que la función de aceleración sea la misma función en el próximo renderizado. Puede usar el enlace 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; }He estado tratando de resolver esto y algo similar, ya que el siguiente código me funciona:
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 }