React-router提供了一些router的核心api,包括Router, Route, Switch等,但是它没有提供
React-router-dom提供了BrowserRouter, Route, Link等api,我们可以通过dom的事件控制路由。
react-router: 实现了路由的核心功能。
react-router-dom: 基于react-router,加入了在浏览器运行环境下的一些功能。
平常用 React-router-dom 居多
安装
$ npm install --save react-router
$ npm install --save react-router-dom
使用
路由器Router就是React的一个组件
Router组件本身只是一个容器,真正的路由要通过Route组件定义。
Route组件定义了URL路径与组件的对应关系
// using ES6 modules
import {
BrowserRouter as Router,
Switch,
Route,
Link,
Redirect,
useParams,
useRouteMatch,
useHistory,
useLocation
} from "react-router-dom";
整个页面路由的根组件 (必需):<Router></Router>
内部路由只显示一个路由 :Switch
重定向:Redirect
React> = 16.8 才能使用一下钩子
注:下面获取参数作为路由组件时,可通过props获取,但是当作为组件时,props获取不到当前的路径对应的信息,所以需要用下面的钩子去获取。但是还有一个条件就是必须在函数组件中使用下面的钩子,且不能再事件的回调中去使用下面钩子
URL参数的键/值对的对象 :useParams()
当前URL 的对象:useLocation()
导航的实例(不可在回调函数里面去获取):useHistory(),拥有跳转等方法,push replace …
尝试匹配以同样的方式在当前的URL: useRouteMatch()
export default function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
</ul>
<hr />
{
/*
A <Switch> looks through all its children <Route>
elements and renders the first one whose path
matches the current URL. Use a <Switch> any time
you have multiple routes, but you want only one
of them to render at a time
*/}
<Switch>
<Route exact path="/">
<Home /