React-router
introduce:
1. Routing is to display different pages or content according to different url addresses
2. Installation: npm install react-router-dom@5
use:
import
import {HashRouter, Route} from 'react-router-dom'
define routes
render() {
return (
<div>
<HashRouter>
<Route path="/home" component={Home} />
<Route path="/second" component={Second} />
<Route path="/mine" component={Mine} />
</HashRouter>
</div>
)
}
(1) Suggestion: Encapsulate the route separately in a js file
(2) Pay attention to first-level routing and multi-level routing
redirect
Meaning: If we don't want users to access a certain route or the route is not in the route we wrote, we can let the component jump to the route we specified.
//模糊匹配,重定向
<Redirect from="/" to="/home" exact />
//exact 精确地
<Route path="*" component={Text} />
nested routes
parent component:
<Route path="/home" component={Home} />
Subassembly:
<Route path="/home/page1" component={Page1} />
<Route path="/home/page2" component={Page2} />
<Redirect from="/home" to="/home/page1" />
Routing Jump
(1) Declarative routing
<NavLink to="/home" activeClassName="ok">home</NavLink>
<NavLink to="/second" activeClassName="ok">second</NavLink>
<NavLink to="/mine" activeClassName="ok">mine</NavLink>
(2) Programmatic routing
- this.props.history.push(routing)
- props.history.push(routing)
-
import {useHistory} from 'react-router-dom' const history = useHistory() history.push(路由)
Routing parameters
(1)
<Route path='/detail/:id' component={Detail} />
Dynamic routing: stands for dynamic, id can be replaced, and can be obtained in props.match.params;
(2)
history.push({
pathname:'/detail',
query:{id}
})
props.location.query.id
(3)
history.push({
pathname:'/detail',
state:{id}
})
props.location.state.id
route interception
<Route path='/test' render={() => {
判断 ? <Home/> : <Login/>
}} />
routing pattern
- HashRouter
- BrowserRouter