1、要引入Redirect
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
2、定义一个flag
this.state = {
loginFlag:false
};
3、render里面判断flag 来决定是否跳转
if(this.state.loginFlag){
return <Redirect to={{ pathname: "/" }} />;
}
4、要执行js跳转
通过js改变loginFlag的状态
改变数据以后会执行一系列的函数 其中也会执行render方法 就可以通过Redirect自己来跳转
doLogin=(e)=>{
e.preventDefault()
let username = this.refs.username.value
let password = this.refs.password.value
console.log(username,password)
if(username=='admin' && password== '123456'){
this.setState({
loginFlag: true
})
}else {
alert('登录失败')
}
}
以下是整个代码
import React , { Component } from 'react'
import { Redirect} from "react-router-dom";
class Login extends Component {
constructor(props){
super(props)//用于父子组件传值 固定写法
this.state={
loginFlag:false
}
}
doLogin=(e)=>{
e.preventDefault()
let username = this.refs.username.value
let password = this.refs.password.value
console.log(username,password)
if(username=='admin' && password== '123456'){
this.setState({
loginFlag: true
})
}else {
alert('登录失败')
}
}
render(){
if(this.state.loginFlag){
return <Redirect to={{ pathname: "/" }} />;
}
return(
<div className='login'>
<h1>登录页面</h1>
<br/> <br/>
<form onSubmit={this.doLogin}>
<input ref='username'/><br/><br/>
<input type='password' ref='password'/><br/><br/>
<input type='submit' value='登录' />
</form>
</div>
)
}
}
export default Login