From b0bdd120dff626f9b988853e4fa48fc6c10e4973 Mon Sep 17 00:00:00 2001 From: sumingcheng Date: Sun, 15 Dec 2024 19:19:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/deviceUtils.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/utils/deviceUtils.js b/src/utils/deviceUtils.js index f3a3a1b2..bf6f6bc9 100644 --- a/src/utils/deviceUtils.js +++ b/src/utils/deviceUtils.js @@ -1,19 +1,28 @@ import React from 'react' +import { throttle } from 'lodash' + export const isMobile = () => { if (typeof window === 'undefined') return false return window.innerWidth <= 768 } export const useIsMobile = () => { - const [isMobileView, setIsMobileView] = React.useState(isMobile()) + const [isMobileView, setIsMobileView] = React.useState(false) React.useEffect(() => { - const handleResize = () => { + setIsMobileView(isMobile()) + + const handleResize = throttle(() => { setIsMobileView(isMobile()) - } + }, 200) window.addEventListener('resize', handleResize) - return () => window.removeEventListener('resize', handleResize) + window.addEventListener('orientationchange', handleResize) + + return () => { + window.removeEventListener('resize', handleResize) + window.removeEventListener('orientationchange', handleResize) + } }, []) return isMobileView