一、React 路由
1 什么是路由?
2 路由安装
npm install react-router-dom@5
3 路由使用
import React from 'react'
import { HashRouter, Route, Redirect, Switch } from 'react-router-dom'
import Two from './Two'
import Three from './Three'
import NotFound from './NotFound'
export default function One() {
return (
<HashRouter>
<Switch>
<Route path="/two" component={Two} />
<Route path="/Three" component={Three} />
{}
<Redirect from="/" to="/two" exact />
{}
<Route component={NotFound} />
</Switch>
</HashRouter>
)
}
4 路由跳转方式
- 声明式导航
<NavLink to="/one" activeClassName="active">One</NavLink>
<NavLink to="/two" activeClassName="active">Two</NavLink>
<NavLink to="/Three" activeClassName="active">Three</NavLink>
- 编程式导航
props.history.push("/one")
this.props.history.push("/one")
import { Redirect, Route, Switch, useHistory } from 'react-router-dom'
const history = useHistory()
history.push('/three')
5 路由传参
<Route path="/two/:id" component={Two} />
<NavLink to="/two/1">点击</NavLink>
console.log(props.match.params.id)
props.history.push({ pathname: '/three', query: { id: 1 } })
console.log(props.location.query.id)
props.history.push({ pathname: '/three', state: { id: 1 } })
console.log(props.location.state.id)
6 路由拦截
<Route path="/three" render={() => <Two/>} />
<Route path="/two" component={Two} />
<Route path="/three" render={() => {
return isAdmin() ? <Three /> : <Four />
}} />
<Route path="/three" render={() => {
return isAdmin() ? <Three /> : <Redirect to="/four" />
}} />
<Route path="/three" render={(props) => {
return isAdmin() ? <Three {...props} /> : <Redirect to="/four" />
}} />
7 子组件使用父组件的路由方法
import React from 'react'
export default function One(props) {
return (
<div><OneChild {...props} /></div>
)
}
function OneChild(props) {
return <div>
<button onClick={() => {
props.history.push("two")
}}>点击</button>
</div>
}
<NavLink to="/two">点击</NavLink>
8 withRouter的应用与原理
import React from 'react'
import { NavLink, withRouter } from 'react-router-dom'
export default function One(props) {
return (
<div><WithOneChild /></div>
)
}
function OneChild(props) {
console.log(props)
return <div>
<button onClick={() => {
props.history.push("two")
}}>点击</button>
</div>
}
const WithOneChild = withRouter(OneChild)