重定向:
1、引入
import {BrowserRouter as Router,Link,Route,Redirect,Switch} from 'react-router-dom'
2、使用
类似于方法,设置好后自动执行
<Redirect to='路由路径' ></Redirect>
动态跳转
this.props.history.push('路由路径',{参数键值对}) 通过this.props.location.state.键名获取
.push({和Link中to属性为对象的格式一样的对象})
this.props.history.go(数值); 根据栈来跳转
this.props.history.goBack();
this.props.history.goForward();
代码示例:
import React,{Component} from 'react'
//import {Route,BrowserRouter,Link} from 'react-router-dom'
//将BrowserRouter重命名为Router
//Redirect重定向需要引入
import {BrowserRouter as Router,Link,Route,Redirect,Switch} from 'react-router-dom'
import { Button } from 'antd';
import './App.css';
function Login(props)
{
console.log(props.location.state.loginState)
if(props.location.state.loginState=='success')
{
return <Redirect to='/admin'></Redirect>
}else{
return <Redirect to='/login'></Redirect>
}
}
let firm=()=>{
let obj={pathname:'/logInfo',state:{loginState:'success'}}
return (
<div>
<h1>表单</h1>
<Link to={obj} >验证页面</Link>
</div>
)
}
class Child extends Component{
constructor()
{
super();
}
render()
{
return(
<div>
<button onClick={this.jump.bind(this)}>跳转到首页</button>
</div>
)
}
jump()
{
this.props.history.push('/',{msg:'来自child'})
{/* this.props.history.push(传入和to属性格式一样的对象)
this.props.history.go(1);
this.props.history.goBack();
this.props.history.goForward();
*/}
}
}
export default class App extends Component{
constructor()
{
super();
}
render()
{
return(
<div>
<Router>
<div>
<Switch>
<Route exact path="/" component={(props)=>{console.log(props.location.state.msg); return <div>首页</div>}}></Route>
<Route path="/form" component={firm}></Route>
<Route path="/login" component={()=><div>登录</div>}></Route>
<Route path="/logInfo" component={Login}></Route>
<Route path="/admin" component={()=><div>admin</div>}></Route>
<Route path="/admin" component={()=><div>admin</div>}></Route>
<Route path="/child" component={Child}></Route>
</Switch>
</div>
</Router>
</div>
)
}
}