修复 页面 闪动

This commit is contained in:
张成
2025-11-05 18:29:20 +08:00
parent c9818b57dc
commit 29fd69d83c

View File

@@ -2,45 +2,88 @@ import React, { useEffect, useState } from "react";
import { View } from "@tarojs/components"; import { View } from "@tarojs/components";
import Taro from "@tarojs/taro"; import Taro from "@tarojs/taro";
import { getCurrentFullPath } from '@/utils'; 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<P extends object>( export default function withAuth<P extends object>(
WrappedComponent: React.ComponentType<P>, WrappedComponent: React.ComponentType<P>,
) { ) {
const ComponentWithAuth: React.FC<P> = (props: P) => { const ComponentWithAuth: React.FC<P> = (props: P) => {
const [authed, setAuthed] = useState(false); const [authed, setAuthed] = useState<boolean | null>(null); // null表示未检查
useEffect(() => { const [isChecking, setIsChecking] = useState(true);
const is_login = check_login_status();
setAuthed(is_login);
// if (!is_login) { useEffect(() => {
// const currentPage = getCurrentFullPath(); const checkAuth = async () => {
// Taro.redirectTo({ setIsChecking(true);
// url: `/login_pages/index/index${ try {
// currentPage ? `?redirect=${encodeURIComponent(currentPage)}` : "" 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 ( if (isChecking || authed === null) {
// <View return (
// style={{ <View
// width: "100vh", style={{
// height: "100vw", width: "100vw",
// backgroundColor: "white", height: "100vh",
// position: "fixed", backgroundColor: "#fff",
// top: 0, position: "fixed",
// left: 0, top: 0,
// zIndex: 999, left: 0,
// }} zIndex: 999,
// /> }}
// ); // 空壳,避免 children 渲染出错 />
// } );
}
// 未登录,显示空白页面(已跳转,这里只是防止渲染)
if (!authed) {
return (
<View
style={{
width: "100vw",
height: "100vh",
backgroundColor: "#fff",
position: "fixed",
top: 0,
left: 0,
zIndex: 999,
}}
/>
);
}
// 已登录,正常渲染组件
return <WrappedComponent {...props} />; return <WrappedComponent {...props} />;
}; };
ComponentWithAuth.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return ComponentWithAuth; return ComponentWithAuth;
} }