import { useState, FormEvent, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '@/shared/context/AuthContext'; import { apiClient } from '@/shared/api/serverClient'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; import { toast } from 'sonner'; export default function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [loading, setLoading] = useState(false); const navigate = useNavigate(); const location = useLocation(); const { login, isAuthenticated } = useAuth(); const from = location.state?.from?.pathname || '/'; // 监听认证状态,登录成功后自动跳转 useEffect(() => { if (isAuthenticated && !loading) { navigate(from, { replace: true }); } }, [isAuthenticated, navigate, from, loading]); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setLoading(true); try { const formData = new URLSearchParams(); formData.append('username', email); formData.append('password', password); const response = await apiClient.post('/auth/login', formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); await login(response.data.access_token); toast.success('登录成功'); // 跳转由 useEffect 监听 isAuthenticated 状态变化自动处理 } catch (error: any) { toast.error(error.response?.data?.detail || '登录失败'); } finally { setLoading(false); } }; return (
XCodeReviewer 请输入您的账号和密码登录
setEmail(e.target.value)} required />
setPassword(e.target.value)} required />
还没有账号? navigate('/register')}>立即注册
); }