| import React, { useEffect } from 'react'; |
| import { useApi } from '@/hooks/request'; |
| import request from '@/utils/request'; |
| import { postUserLogin} from '@/api/auth'; |
| import { useAppDispatch } from '@/hooks/store'; |
| import { RootState } from '@/store'; |
| import style from './login.module.css'; |
| import { useState } from 'react'; |
| import { useSelector } from 'react-redux'; |
| import { useNavigate } from 'react-router'; |
| import logo from '&/assets/logo.png'; |
| import { getUserInfo } from '@/api/user'; |
| import debounce from 'lodash/debounce'; |
| import {message} from 'antd'; |
| |
| |
| const Login: React.FC = () => { |
| const [email, setEmail] = useState(''); |
| const [password, setPassword] = useState(''); |
| const dispatch = useAppDispatch(); |
| const { refresh: postUserLoginRefresh } = useApi(() => request.post(postUserLogin, {email, password}), false); |
| const { refresh: getUserInfoRefresh } = useApi(() => request.get(getUserInfo), false); |
| const [messageApi, contextHolder] = message.useMessage(); |
| |
| const nav = useNavigate(); |
| const showErrorMessage = async (message: string) => { |
| messageApi.error(message); |
| }; |
| const handleLogin = debounce(async () => { |
| try { |
| const res = await postUserLoginRefresh(); |
| console.log(res); |
| if (res == null || (res as any).error) { |
| throw new Error('登录失败'); |
| } |
| dispatch({ type: "user/login", payload: res }); |
| |
| const userInfo = await getUserInfoRefresh(); |
| if (userInfo == null || (userInfo as any).error) { |
| throw new Error('获取用户信息失败'); |
| } |
| dispatch({ type: "user/getUserInfo", payload: userInfo }); |
| nav('/'); |
| } catch (error) { |
| // 将错误信息传递给一个异步函数 |
| showErrorMessage('登录失败,请检查您的用户名和密码'); |
| } |
| }, 1000) as () => void; |
| |
| const handleLogoClick = () => { |
| nav('/'); |
| } |
| return ( |
| <div className={style.form}> |
| {contextHolder} |
| <img className={style.logo} src={logo} alt="logo" onClick={handleLogoClick}></img> |
| <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} className={style.email} placeholder="Enter your email" /> |
| <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} className={style.password} placeholder="Enter your password" /> |
| <button className={style.submit} onClick={() => handleLogin()}>登录</button> |
| <button className={style.register}>注册</button> |
| <button className={style.forget}> 忘记密码</button> |
| </div> |
| ); |
| }; |
| |
| export default Login; |