React路由
安装
如果想要使用react路由,则需要安装react-router-dom
在该模块中,我们会经常使用BrowserRouter,HashRouter,Route,Switch,Redirect,Link,NavLink
使用
import React, { Component } from 'react'
import { HashRoter as Router, Route } from 'react-router-dom'
class Router extends Component {
constructor (props) {
super(props)
}
render () {
reture (
<Router>
// 每个路由配置都是一个Route
<Route exact path="/" component={}></Route>
<Route></Route>
<Route></Route>
<Route></Route>
</Router>
)
}
}
嵌套路由
import React, { Component } from 'react'
import { HashRoter as Router, Route } from 'react-router-dom'
class Router extends Component {
constructor (props) {
super(props)
}
render () {
return (
<Router>
// 每个路由配置都是一个Route
<Route exact path="/" component={}></Route>
// 嵌套路由有两种方式 1 使用render和父路由写在一起,需要给子组件中添加this.props.children
<Route render={() => (
<组件>
<Route path="" componet={}></Route>
</组件>
)}></Route>
// 2 把子路由写在对应的组件中
<Route exact path="/" component={Child}></Route>
</Router>
)
}
}
Child.js
import React, { Component } from 'react'
import { Route } from 'react-router-dom'
class Router extends Component {
constructor (props) {
super(props)
}
render () {
return (
<div>
<Route path="" component={}></Route>
<Route path="" component={}></Route>
<Route path="" component={}></Route>
<Route path="" component={}></Route>
</div>
)
}
}
参数接收
params 动态路由
<Route to="/demo/:id"></Route>
this.props.match.params.id // 刷新页面不会消失
query
需要借助Link进行页面的跳转
<Link to={{pathname: '/demo', query: {id: 1}}}></Link>
this.props.location.query.id // 刷新页面后数据消失
state
需要借助Link进行页面的跳转