diff --git a/src/components/Auth/index.tsx b/src/components/Auth/index.tsx
index 6cbf848..13644dc 100644
--- a/src/components/Auth/index.tsx
+++ b/src/components/Auth/index.tsx
@@ -2,45 +2,88 @@ import React, { useEffect, useState } from "react";
import { View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { getCurrentFullPath } from '@/utils';
-import { check_login_status } from "@/services/loginService";
+import { check_login_status, clear_login_state } from "@/services/loginService";
export default function withAuth
(
WrappedComponent: React.ComponentType
,
) {
const ComponentWithAuth: React.FC
= (props: P) => {
- const [authed, setAuthed] = useState(false);
- useEffect(() => {
- const is_login = check_login_status();
- setAuthed(is_login);
+ const [authed, setAuthed] = useState(null); // null表示未检查
+ const [isChecking, setIsChecking] = useState(true);
- // if (!is_login) {
- // const currentPage = getCurrentFullPath();
- // Taro.redirectTo({
- // url: `/login_pages/index/index${
- // currentPage ? `?redirect=${encodeURIComponent(currentPage)}` : ""
- // }`,
- // });
- // }
+ useEffect(() => {
+ const checkAuth = async () => {
+ setIsChecking(true);
+ try {
+ const is_login = check_login_status();
+
+ if (!is_login) {
+ // 未登录,清除可能过期的状态
+ clear_login_state();
+ const currentPage = getCurrentFullPath();
+ // 跳转到登录页,并保存当前页面路径用于登录后跳转
+ (Taro as any).redirectTo({
+ url: `/login_pages/index/index${
+ currentPage ? `?redirect=${encodeURIComponent(currentPage)}` : ""
+ }`,
+ });
+ setAuthed(false);
+ return;
+ }
+
+ setAuthed(true);
+ } catch (error) {
+ console.error('检查登录状态失败:', error);
+ clear_login_state();
+ (Taro as any).redirectTo({ url: '/login_pages/index/index' });
+ setAuthed(false);
+ } finally {
+ setIsChecking(false);
+ }
+ };
+
+ checkAuth();
}, []);
- // if (!authed) {
- // return (
- //
- // ); // 空壳,避免 children 渲染出错
- // }
+ // 正在检查登录状态,显示空白页面避免闪烁
+ if (isChecking || authed === null) {
+ return (
+
+ );
+ }
+ // 未登录,显示空白页面(已跳转,这里只是防止渲染)
+ if (!authed) {
+ return (
+
+ );
+ }
+
+ // 已登录,正常渲染组件
return ;
};
+ ComponentWithAuth.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
+
return ComponentWithAuth;
}