react 路由重定向、动态跳转

重定向:
	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>
        )
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值