【React.js 13】react-router4基础知识-2
2018-04-02 本文已影响94人
IUVO
除了上一篇所讲的3个入门组件
BrowserRouter
、Router
、Link
。
react-router4
其实还有更多的组件使用方式。
依据上一篇文章的案例继续改写。
带url
参数的Route
:
Route
组件参数可以用冒号标识参数,我们举个例子来看:
1、在index.js
文件中直接新增一个测试类(后面用完就可以删了)
class Test extends Component {
render(){
console.log(this.props)
return (
<h2>测试组件,location参数:{this.props.match.params.location}</h2>
)
}
}
2、修改路由渲染模板,仅留下两个:
<Route path='/' exact component={App}></Route>{/* exact代表完全匹配 */}
<Route path='/:location' component={Test}></Route>
3、渲染后,由于只有/
路径是精准匹配的,其他则是模糊匹配,所以两条Link
(<Link to='/tecDep'>技术部</Link>
和<Link to='/HRDep'>人事部</Link>
)被匹配为/
路径加location
参数。


大致明白Route
的url
参数是做什么用的了吧。
Switch
组件:
当然,要使用Switch
组件,还是要先import
一下:
import { BrowserRouter, Route, Link ,Switch } from 'react-router-dom'
Switch
组件主要的作用就是在于只渲染命中的第一个Route
:
<Switch>
{/* 路由的渲染模板,渲染哪个路由,就写哪个路径 */}
<Route path='/' exact component={App}></Route>{/* exact代表完全匹配 */}
{/* 以下两个组件不存在,所以我们先定义两个无状态组件 */}
<Route path='/tecDep' component={tecDep}></Route>
<Route path='/HRDep' component={HRDep}></Route>
<Route path='/:location' component={Test}></Route>
</Switch>
如果我们不使用Switch
组件就会出现只要是匹配上的路径,都会被渲染出来:

使用
Switch
后:
这样,我们就能做一个类似404 NotFound
的页面,只要未命中,就一直匹配到最后一个去,我们随便在地址输入一个:

Redirect
组件:
删掉之前测试的组件,我们来写写别的案例。
当然,要使用Redirect
组件,还是要先import
一下:
import { BrowserRouter, Route, Link ,Redirect } from 'react-router-dom'
在路由渲染模板里加入Redirect
:
<Redirect to='/HRDep' ></Redirect>
{/* 路由的渲染模板,渲染哪个路由,就写哪个路径 */}
<Route path='/' exact component={App}></Route>{/* exact代表完全匹配 */}
{/* 以下两个组件不存在,所以我们先定义两个无状态组件 */}
<Route path='/tecDep' component={tecDep}></Route>
<Route path='/HRDep' component={HRDep}></Route>
你会发现,每次刷新,就会被强制重定向到/HRDep
路径。