点击切换路由
修改引入方式变成非Hash模式
import {BrowserRouter as Router,Route,Switch,Redirect} from "react-router-dom"
1:在Home.js中
改写代码加一个a标签 测试代码的跳转 通过a标签
import React, { Component } from 'react'
export default class Home extends Component {
render() {
console.log(this.props);
return (
<div>
我是首页
<a href="/mine">去个人页面</a>
</div>
)
}
}
2:点击跳转 代码如下 声明一个按钮 给按钮绑定点击事件
goToMine=()=>{
this.props.history.push("/mine");
}
render() {
console.log(this.props);
return (
<div>
我是首页
<a href="/mine">去个人页面</a>
<button onClick={()=>this.goToMine()}>点击事件的跳转</button>
</div>
)
}
很多时候 我们可以通过this.props将路由传递的信息 全部进行输出 方便研究
3:带参数的处理
<Switch>
<Route path="/center" component={Center} excat></Route>
<Route path="/mine" component={Mine} excat>
</Route>
<Route path="/order/:id" component={Order} exact></Route>
<Route path="/" component={Home} exact>
</Route>
</Switch>
4:访问的地方
<ul>
<li><a href="/order/5">我的订单</a></li>
</ul>
5:在view中可以接收到参数
import React, { Component } from 'react'
export default class Order extends Component {
render() {
// console.log(this.props);
return (
<div>
我的订单信息{this.props.match.params.id}
</div>
)
}
}
6:也可以手动的隐式传参
<button onClick={()=>{this.props.history.push({
pathname:"/order",
state:{
id:1111
}
})}}>点击跳转</button>
7:接收方法的改变
return (
<div>
{/* 我的订单信息{this.props.match.params.id} */}
{/*点击过来的参数为*/}
{this.props.history.location.state.id}
</div>
8:还需要修改路由的地方 把后面的/:id去除掉
<Route path="/order" component={Order} excat></Route>