import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useNavigate } from 'react-router-dom'; import { checkAuthThunk, loginThunk } from '../../store/auth/auth.thunk'; export default function Login() { const dispatch = useDispatch(); const navigate = useNavigate(); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [errors, setErrors] = useState({}); const [submitted, setSubmitted] = useState(false); const { user } = useSelector((state) => state.auth); useEffect(() => { handleCheckAuth(); }, [dispatch]); const handleCheckAuth = async () => { console.log('login page handleCheckAuth'); await dispatch(checkAuthThunk()).unwrap(); if (user) navigate('/'); }; const validateForm = () => { const newErrors = {}; if (!username) { newErrors.username = 'Username is required'; } if (!password) { newErrors.password = 'Password is required'; } else if (password.length < 6) { newErrors.password = 'Password must be at least 6 characters'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = (e) => { e.preventDefault(); setSubmitted(true); console.log(validateForm()); if (validateForm()) { console.log('Form submitted successfully!'); console.log('Username:', username); console.log('Password:', password); dispatch(loginThunk({ username, password })); } }; return (
OOIN 智能知识库
setUsername(e.target.value.trim())} > {submitted && errors.username &&
{errors.username}
}
setPassword(e.target.value.trim())} > {submitted && errors.password &&
{errors.password}
}
Forgot password?
Need Account?
); }