feat: 创建 Redux Device Slice(简化版)
注册到 Redux Store
This commit is contained in:
52
src/store/slices/deviceSlice.js
Normal file
52
src/store/slices/deviceSlice.js
Normal file
@@ -0,0 +1,52 @@
|
||||
// src/store/slices/deviceSlice.js
|
||||
import { createSlice } from '@reduxjs/toolkit';
|
||||
|
||||
/**
|
||||
* 检测当前设备是否为移动设备
|
||||
*
|
||||
* 判断逻辑:
|
||||
* 1. User Agent 检测(移动设备标识)
|
||||
* 2. 屏幕宽度检测(<= 768px)
|
||||
* 3. 触摸屏检测(支持触摸事件)
|
||||
*
|
||||
* @returns {boolean} true 表示移动设备,false 表示桌面设备
|
||||
*/
|
||||
const detectIsMobile = () => {
|
||||
const userAgent = navigator.userAgent || navigator.vendor || window.opera;
|
||||
const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
|
||||
const isMobileUA = mobileRegex.test(userAgent);
|
||||
const isMobileWidth = window.innerWidth <= 768;
|
||||
const hasTouchScreen = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
|
||||
|
||||
return isMobileUA || (isMobileWidth && hasTouchScreen);
|
||||
};
|
||||
|
||||
const initialState = {
|
||||
isMobile: detectIsMobile(),
|
||||
};
|
||||
|
||||
const deviceSlice = createSlice({
|
||||
name: 'device',
|
||||
initialState,
|
||||
reducers: {
|
||||
/**
|
||||
* 更新屏幕尺寸状态
|
||||
*
|
||||
* 使用场景:
|
||||
* - 监听 window resize 事件时调用
|
||||
* - 屏幕方向变化时调用(orientationchange)
|
||||
*/
|
||||
updateScreenSize: (state) => {
|
||||
state.isMobile = detectIsMobile();
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Actions
|
||||
export const { updateScreenSize } = deviceSlice.actions;
|
||||
|
||||
// Selectors
|
||||
export const selectIsMobile = (state) => state.device.isMobile;
|
||||
|
||||
// Reducer
|
||||
export default deviceSlice.reducer;
|
||||
Reference in New Issue
Block a user