FEAT => 本次更新项目为:
设备绑定指引
This commit is contained in:
90
nkebao/src/components/DeviceGuard/index.tsx
Normal file
90
nkebao/src/components/DeviceGuard/index.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import React, { useEffect, useState, useMemo } from "react";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import { useDeviceStore } from "@/store/module/device";
|
||||
import { useUserStore } from "@/store/module/user";
|
||||
import { updateDeviceCount } from "@/utils/device";
|
||||
|
||||
interface DeviceGuardProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const DeviceGuard: React.FC<DeviceGuardProps> = ({ children }) => {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { isLoggedIn } = useUserStore();
|
||||
const { setDeviceCount } = useDeviceStore();
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
|
||||
// 不需要设备检查的路径
|
||||
const EXEMPT_PATHS = useMemo(
|
||||
() => ["/login", "/guide", "/register", "/forgot-password"],
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const checkDeviceStatus = async () => {
|
||||
// 如果用户未登录,不需要检查设备状态
|
||||
if (!isLoggedIn) {
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果当前路径是豁免路径,不需要检查设备状态
|
||||
if (EXEMPT_PATHS.includes(location.pathname)) {
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 从API获取最新的设备数量并更新到store
|
||||
const currentDeviceCount = await updateDeviceCount(setDeviceCount);
|
||||
|
||||
// 如果设备数量为0且不在guide页面,跳转到guide页面
|
||||
if (currentDeviceCount === 0 && location.pathname !== "/guide") {
|
||||
navigate("/guide");
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果设备数量大于0且在guide页面,跳转到首页
|
||||
if (currentDeviceCount > 0 && location.pathname === "/guide") {
|
||||
navigate("/");
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("检查设备状态失败:", error);
|
||||
// 如果检查失败,默认跳转到guide页面
|
||||
if (location.pathname !== "/guide") {
|
||||
navigate("/guide");
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
setIsChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkDeviceStatus();
|
||||
}, [isLoggedIn, location.pathname, navigate, setDeviceCount, EXEMPT_PATHS]);
|
||||
|
||||
// 如果正在检查,显示加载状态
|
||||
if (isChecking) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
height: "100vh",
|
||||
background: "var(--primary-color)",
|
||||
}}
|
||||
>
|
||||
<div style={{ color: "white", fontSize: "16px" }}>
|
||||
检查设备状态中...
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
export default DeviceGuard;
|
||||
Reference in New Issue
Block a user