Switch组件实现了在同一个组件中面对不同参数进行不同形式的展现
Switch的具体用法
在需要进行传入不同参数的组件中添加Switch组件(如下面代码中的A组件),它实现了在组件中使用Route,让React-Router的使用更加灵活,在Switch中Route的匹配规则是从上到下匹配,当匹配到一个符合的路由时停止匹配,返回第一个匹配的Route
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import {HashRouter as Router,Route,Link,Switch} from 'react-router-dom'
class A extends Component {
constructor(props){
super(props)
}
render() {
console.log(this.props.match.params)
return (
<div>
Component A
<Switch>
<Route exact path={`${this.props.match.path}`} render={(route)=>{
return <div>当前组件无参数</div>
}}></Route>
<Route path={`${this.props.match.path}/:id`} render={(route)=>{
return <div>当前组件的参数是 {route.match.params.id}</div>
}}></Route>
</Switch>
</div>
)
}
}
class B extends Component {
render() {
return (
<div>Component B</div>
)
}
}
class Wrapper extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<Link to='/a/123'>有参数组件A</Link>
<br/>
<Link to='/a'>无参数组件A</Link>
<br/>
<Link to='/b'>组件B</Link>
{this.props.children}
</div>
)
}
}
ReactDOM.render(
<Router>
<Wrapper>
<Route path="/a" component={A}></Route>
<Route path='/b' component={B}></Route>
</Wrapper>
</Router>
,
document.querySelector('#app')
)
其他方法
除了使用Switch组件以外,还可以通过直接在Link中设置正则来将不同路由引入到同一个页面中
比如:<Route path='/product/save/:pid?' component={ProductSave}></Route>
就可以将/product/save
和/product/save/:pid
两个路由的情况下都加载ProductSave
组件