文章目录
- React实现页面路由的模块:
react-router-dom
- 在 React Router 中有三种类型的组件:路由器组件,路由匹配组件,导航组件。这些组件都来自于
react-router-dom
。
1 路由器组件:< HashRouter > < BrowserRouter >
对于每一个 React Router 应用来说,都应该有一个路由器组件,它们会为应用创建一个专用的 history
对象。
针对 Web 项目,react-router-dom
提供了 <BrowserRouter>
和 <HashRouter>
。
主要区别:
- BrowserRouter 和 HashRouter 都可以实现前端路由的功能
- BrowserRouter 实现的是单页面的路由切换
- HashRouter 实现的是全局路由切换
从原理上:
- HashRouter在路径中包含了#,相当于HTML的锚点定位。(# 符号的英文叫hash,所以叫HashRouter,和散列没关系哦)
- 而BrowserRouter使用的是HTML5的新特性History,没有HashRouter(锚点定位)那样通用,低版本浏览器可能不支持。
从用法上:
- BrowserRouter进行组件跳转时可以传递任意参数实现组件间的通信,
- HashRouter不能(除非手动拼接URL字符串),因此一般配合Redux使用,实现组件间的数据通信。
其实就是路由的hash和history两种模式,并且这两个组件是路由的容器,必须在最外层。
<HashRouter>
...
</HashRouter>
<BrowserRouter>
...
</BrowserRouter>
2. 路由
2.1 < Route >
-
路由匹配是通过比较
<Route>
组件的path
属性和当前地址的 pathname 实现的 -
如果匹配则渲染当前路由组件的内容,如果不匹配则渲染 null。
-
注意:没有提供
path
属性的<Route>
组件将总是匹配。
2.1.1 < Route element >
- Route的 render 或 component 改为 element
import Profile from './Profile';
// v5
<Route path=":userId" component={Profile} />
<Route
path=":userId"
render={routeProps => (
<Profile routeProps={routeProps} animate={true} />
)}
/>
// v6
<Route path=":userId" element={<Profile />} />
<Route path=":userId" element={<Profile animate={true} />} />
<Route path=":userId" element={<Profile animate={true} /> />
function Profile({ animate }) {
const params = useParams();
const location = useLocation();
}
通过这种形式:
1. 可以向组件传 props,如上面的 animate={true}
2. 因为有了 hook 的出现,所以不必再通过 renderProps 向组件传递路由的一些 props,我们可以通过useParams、useLocation 就可以拿到这些信息
- v6 Route 的 children 是用于嵌套路由
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/users" element&