blob: 8043007a035bb225e33c0844aa270084cc0fe5e4 [file] [log] [blame]
2230101462240ab2025-06-07 09:28:16 +08001import { Loading3QuartersOutlined, LockOutlined, MailOutlined } from '@ant-design/icons';
2import { Button, Checkbox, Flex, Form, Input } from 'antd';
3import { NavLink, useNavigate } from 'react-router';
4import { useAppDispatch, useAppSelector } from '../../store/hooks';
5import { loginUser } from './authSlice';
6import { useEffect, useRef } from 'react';
7import useMessage from 'antd/es/message/useMessage';
22301014bc4616f2025-06-03 16:59:44 +08008
2230101462240ab2025-06-07 09:28:16 +08009// 定义 Form 表单的字段类型
10interface FormValues {
11 email: string;
12 password: string;
13 remember: boolean;
14}
15
22301014bc4616f2025-06-03 16:59:44 +080016function Login() {
2230101462240ab2025-06-07 09:28:16 +080017 const dispatch = useAppDispatch();
18 const auth = useAppSelector(state => (state.auth));
19 const [messageApi, Message] = useMessage()
20 const nav = useRef(useNavigate())
21
22 useEffect(() => {
23 if (auth.isAuth) {
24 nav.current('/');
25 }
26 if (!auth.loading && auth.error) {
27 messageApi.error(auth.error);
28 }
29 }, [auth, messageApi, nav])
30 // 给 onFinish 参数添加类型
31 const onFinish = async (values: FormValues) => {
32 try {
33 await dispatch(loginUser({ email: values.email, password: values.password }));
34 } catch (error) {
35 console.error('登录失败', error);
36 }
22301014bc4616f2025-06-03 16:59:44 +080037 };
38
39 return (
40 <Form
41 name="login"
42 initialValues={{ remember: true }}
22301014bc4616f2025-06-03 16:59:44 +080043 onFinish={onFinish}
44 >
2230101462240ab2025-06-07 09:28:16 +080045 {Message}
22301014bc4616f2025-06-03 16:59:44 +080046 <h2>登录</h2>
47 <Form.Item
48 name="email"
49 rules={[{ required: true, message: '请输入你的账号(注册邮箱)!' }, { type: 'email', message: '请输入正确的邮箱' }]}
50 >
51 <Input prefix={<MailOutlined />} placeholder="账号(注册邮箱)" />
52 </Form.Item>
53 <Form.Item
54 name="password"
55 rules={[{ required: true, message: '请输入你的密码!' }]}
56 >
57 <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
58 </Form.Item>
59 <Form.Item>
60 <Flex justify="space-between" align="center">
61 <Form.Item name="remember" valuePropName="checked" noStyle>
62 <Checkbox>自动登录</Checkbox>
63 </Form.Item>
2230101462240ab2025-06-07 09:28:16 +080064 <NavLink to="/forget"> 忘记密码 </NavLink>
22301014bc4616f2025-06-03 16:59:44 +080065 </Flex>
66 </Form.Item>
67
68 <Form.Item>
69 <Button block type="primary" htmlType="submit">
2230101462240ab2025-06-07 09:28:16 +080070 {auth.loading ? (
71 <><Loading3QuartersOutlined /></>
72 ) : (
73 <>登录</>
74 )
75 }
22301014bc4616f2025-06-03 16:59:44 +080076 </Button>
2230101462240ab2025-06-07 09:28:16 +080077 <NavLink to="/register">注册</NavLink>
22301014bc4616f2025-06-03 16:59:44 +080078 </Form.Item>
79 </Form>
80 );
2230101462240ab2025-06-07 09:28:16 +080081}
22301014bc4616f2025-06-03 16:59:44 +080082
2230101462240ab2025-06-07 09:28:16 +080083export default Login;