退出按钮使用Link包裹可以替代this.props.history.push('/')方法吗?

来源:7-3 根据登录权限决定页面展示(3)

不厌_

2021-08-31 18:09:36

如题,使用link包裹感觉效果跟this.props.history.push('/')方法一样。


相关代码:

​import React, { Component } from "react";
import { Link, withRouter } from 'react-router-dom';
import axios from 'axios';
import { Modal, Button, Input, message } from 'antd';
import "./style.css";


class Login extends Component {

constructor(props) {
super(props);
this.state = {
login: false,
modal: false,
user: '',
password: ''

};
// 强制绑定this
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
this.changePassword = this.changePassword.bind(this);
this.changeUser = this.changeUser.bind(this);
this.checkLogin = this.checkLogin.bind(this);
this.logout = this.logout.bind(this);
}
// 登录按钮点击后显示登录界面
showModal() {
this.setState({
modal: true
})
}
// 登录界面OK按钮点击后获取用户名以及密码,通过地址栏上携带的方式发送给服务器
checkLogin() {
const { user, password } = this.state;
const url = `http://www.dell-lee.com/react/api/login.json?user=${user}&password=${password}`;
axios.get(url, { withCredentials: true }).then(res => {
const login = res.data.data.login;
// 服务器做出判断后返回数据,然后提示用户是否登录成功
// 登录成功后登录界面消失,登录按钮变为退出按钮
if (login) {
message.success('登陆成功');
this.setState({
login: true,
modal: false,
})
} else {
message.error('登录失败');
}
})
}
hideModal() {
this.setState({
modal: false
})
}

// 用户名输入框输入后改变user数据,react改变数据后会自动重新渲染在页面上
changeUser(e) {
this.setState({
user: e.target.value
})
}

// 密码输入框输入后改变password数据,react改变数据后会自动重新渲染在页面上
changePassword(e) {
this.setState({
password: e.target.value
})
}

// 点击退出后发送请求,告诉服务器已经退出登录,并且按钮显示为登录
logout() {
axios.get('http://www.dell-lee.com/react/api/logout.json', {
withCredentials: true
})
.then(res => {
const data = res.data.data;
if (data.logout) {
this.setState({
login: false
});
};
// 点击退出按钮后返回首页
// this.props.history.push('/');
})
}
render() {
const { login } = this.state;
return (
<div className="login">
{/* // 如果在已经登录则显示退出按钮,未登录则显示登录按钮 */}
{login ?<Link to="/"><Button type="primary" onClick={this.logout}>退出</Button></Link>:
<Button type="primary" onClick={this.showModal}>登录</Button>
}
{/* vip按钮 */}
<Link to='/vip'>
<Button
type="primary"
style={{ marginLeft: 10 }}
>
Vip
</Button>
</Link>
{/* 登录界面 */}
<Modal
title="登陆"
visible={this.state.modal}
onOk={this.checkLogin}
onCancel={this.hideModal}
>
<Input
placeholder='请输入用户名'
style={{ marginBottom: 10 }}
value={this.state.user}
onChange={this.changeUser}
/>
<Input
placeholder='请输入密码'
type='password'
value={this.state.password}
onChange={this.changePassword}
/>
</Modal>
</div>
)
}
componentDidMount() {
// 页面加载时发送请求判断是否已经登录,然后改变按钮的显示
axios.get('http://www.dell-lee.com/react/api/isLogin.json', {
withCredentials: true
})
.then(res => {
const login = res.data.data.login;
this.setState({ login })
})
}
}

// 使用withRouter,然后即可使用路由相关方法
export default Login;


写回答

1回答

好帮手慕星星

2021-08-31

同学你好,是可以代替的,粘贴的代码没问题,很棒!

祝学习愉快~

0

0 学习 · 15276 问题

查看课程