React Router 的意义是什么
React router, What is the point of it
一句话:让 SPA有「URL」这个概念—— 把地址栏和当前渲染哪个组件对应起来, 不刷新页面就能切换。
它解决四件事:
- URL ↔ 组件的映射
- 前进后退能用—— 接管
historyAPI - 深链接可分享—— 发给别人能直接打开那个页面
- 嵌套路由—— 布局层和内容层分开 (
Outlet)
核心 API:BrowserRouter、Routes / Route、Link /NavLink、useNavigate、useParams、useSearchParams、Outlet。
三个实践要点:
- 用
Link不要用<a>—— 后者会真的刷新整页, SPA 的意义就没了。 BrowserRouter需要服务端 把所有路径都回退到index.html, 否则刷新子路由会 404。 没法配服务器就用HashRouter。这题很常问。- 配
React.lazy按路由切代码(#347)。
会追问:「路由守卫怎么做?」—— React Router 没有内置守卫, 自己写一个包装组件: 没登录就 <Navigate to="/login" />。
In one line: it gives an SPA the concept of a URL — it maps the address bar to whichever component is rendered, and switches between them without a page reload.
It solves four things:
- Mapping URLs to components
- Back and forward work — it takes over the
historyAPI - Deep links are shareable — send one to someone and it opens that page directly
- Nested routes — the layout layer and the content layer stay separate (
Outlet)
The core API: BrowserRouter, Routes / Route, Link / NavLink, useNavigate, useParams, useSearchParams, Outlet.
Three practical points:
- Use
Link, not<a>— an anchor really does reload the whole page, which throws away the point of an SPA. BrowserRouterneeds the server to fall back toindex.htmlfor every path, otherwise refreshing a nested route 404s. If you cannot configure the server, useHashRouter. This one comes up a lot.- Pair it with
React.lazyto split code per route (#347).
Follow-up: “How do you do route guards?” — React Router has none built in; you write a wrapper component yourself: if the user is not signed in, render <Navigate to="/login" />.