react+antd实现登录退出功能

2021-08-20   阅读:283   分类:前端    标签: React

本文实现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>

【腾讯云】爆款1核2G云服务器首年48元,还有iPad Pro、Bose耳机、京东卡等你来抽!

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://www.tpxhm.com/fdetail/791.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸 头像

简忆博客
勤于学习,乐于分享。

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×