Refactor ProtectedRoute component to properly handle navigation in React lifecycle

This commit is contained in:
yangdx
2025-03-20 12:41:02 +08:00
parent 08ae9c5825
commit 8742ec3625

View File

@@ -67,32 +67,31 @@ const ProtectedRoute = ({ children }: ProtectedRouteProps) => {
} }
}, [isAuthenticated]) }, [isAuthenticated])
// Show nothing while checking auth status // Handle navigation when authentication status changes
if (isChecking) { useEffect(() => {
return null if (!isChecking && !isAuthenticated) {
}
// After checking, if still not authenticated
if (!isAuthenticated) {
// Get current path and check if it's a direct access
const currentPath = window.location.hash.slice(1); // Remove the '#' from hash const currentPath = window.location.hash.slice(1); // Remove the '#' from hash
const isLoginPage = currentPath === '/login'; const isLoginPage = currentPath === '/login';
// Skip redirect if already on login page
if (isLoginPage) {
return null;
}
// For non-login pages, handle state reset and navigation
if (!isLoginPage) { if (!isLoginPage) {
// Use navigation service for redirection // Use navigation service for redirection
console.log('Not authenticated, redirecting to login'); console.log('Not authenticated, redirecting to login');
navigationService.navigateToLogin(); navigationService.navigateToLogin();
}
}
}, [isChecking, isAuthenticated]);
// Show nothing while checking auth status or when not authenticated on login page
if (isChecking || (!isAuthenticated && window.location.hash.slice(1) === '/login')) {
return null; return null;
} }
// Show children only when authenticated
if (!isAuthenticated) {
return null;
} }
return <>{children}</> return <>{children}</>;
} }
const AppContent = () => { const AppContent = () => {