本文实现react+antd框架实现登录记录token功能和退出功能
一、登录功能:
1、 页面代码部分
import React from 'react' import { Form, Input, Button, Image, message } from 'antd'; import { UserOutlined, LockOutlined, BarcodeOutlined } from '@ant-design/icons'; function Login(props) { return ( <div className="login-box"> <div className="login-min"> <div className="avatar_box"> <img src="./logo192.png" alt="" /> </div> <Form name="normal_login" className="login-form" onFinish={onFinish}> <Form.Item name="username" rules={[{ required: true, message: '请输入账号' }]} className="username" > <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" size="large"/> </Form.Item> <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]} > <Input prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="密码" size="large" /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" className="login-form-button" size="large">登录</Button> </Form.Item> </Form> </div> </div> ) } export default Login
2、 页面逻辑代码部分
import React from 'react' import { Form, Input, Button, Image, message } from 'antd'; import { UserOutlined, LockOutlined, BarcodeOutlined } from '@ant-design/icons'; import { setToken } from '../../utils/auth' import { loginApi } from '../../utils/service'; function Login(props) { const onFinish = (values) => { // console.log('Success:', values); loginApi({ username: values.username, password: values.password, }).then(res=>{ console.log(res) if(res.code===0){ // console.log(res.data.token) setToken(res.data.token) props.history.push('/admin/wecome') message.success(res.msg) }else{ message.error(res.msg) } }).catch(err=>{ message.error('服务器故障') }) }; } export default Login
3、 axios请求接口部分封装,详见这篇文章:react封装axios请求接口
最终效果:
二、退出功能
1、编写退出方法:清除token并跳转至登录页面
const Logout = () => { clearToken(); props.history.push('/login') message.success('退出成功') };
2、放置退出按钮
<div className="admin"> <span>admin</span> <span onClick={Logout}><PoweroffOutlined /></span> </div>
文章评论(0)