feat: 添加设备检测功能

This commit is contained in:
zdl
2025-11-26 11:03:13 +08:00
parent 2fcc341213
commit ee78e00d3b
2 changed files with 57 additions and 0 deletions

View File

@@ -28,6 +28,7 @@ import { useGlobalErrorHandler } from './hooks/useGlobalErrorHandler';
// Redux // Redux
import { initializePostHog } from './store/slices/posthogSlice'; import { initializePostHog } from './store/slices/posthogSlice';
import { updateScreenSize } from './store/slices/deviceSlice';
// Utils // Utils
import { logger } from './utils/logger'; import { logger } from './utils/logger';
@@ -63,6 +64,27 @@ function AppContent() {
performanceMonitor.mark('react-ready'); performanceMonitor.mark('react-ready');
}, []); }, []);
// 📱 设备检测:监听窗口尺寸变化
useEffect(() => {
let resizeTimer;
const handleResize = () => {
// 防抖:避免频繁触发
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
dispatch(updateScreenSize());
}, 150);
};
window.addEventListener('resize', handleResize);
window.addEventListener('orientationchange', handleResize);
return () => {
clearTimeout(resizeTimer);
window.removeEventListener('resize', handleResize);
window.removeEventListener('orientationchange', handleResize);
};
}, [dispatch]);
// ✅ 首次访问追踪 // ✅ 首次访问追踪
useEffect(() => { useEffect(() => {
const hasVisited = localStorage.getItem('has_visited'); const hasVisited = localStorage.getItem('has_visited');

35
src/hooks/useDevice.js Normal file
View File

@@ -0,0 +1,35 @@
/**
* useDevice Hook
*
* 封装设备类型检测,提供简洁的 API 供组件使用
*
* @example
* const { isMobile, isTablet, isDesktop, deviceType } = useDevice();
*
* if (isMobile) return <MobileView />;
* if (isTablet) return <TabletView />;
* return <DesktopView />;
*/
import { useSelector } from 'react-redux';
import {
selectIsMobile,
selectIsTablet,
selectIsDesktop,
selectDeviceType,
} from '@/store/slices/deviceSlice';
export const useDevice = () => {
const isMobile = useSelector(selectIsMobile);
const isTablet = useSelector(selectIsTablet);
const isDesktop = useSelector(selectIsDesktop);
const deviceType = useSelector(selectDeviceType);
return {
isMobile,
isTablet,
isDesktop,
deviceType,
};
};
export default useDevice;