DrillLab
第 80 / 105 道80 / 105 · #334

React Router 的意义是什么

React router, What is the point of it

先自己答,再往下看Answer it yourself first

一句话:让 SPA有「URL」这个概念—— 把地址栏和当前渲染哪个组件对应起来, 不刷新页面就能切换。

它解决四件事:

  • URL ↔ 组件的映射
  • 前进后退能用—— 接管 history API
  • 深链接可分享—— 发给别人能直接打开那个页面
  • 嵌套路由—— 布局层和内容层分开 (Outlet

核心 API:BrowserRouterRoutes / RouteLink /NavLinkuseNavigateuseParamsuseSearchParamsOutlet

三个实践要点:

  • 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 history API
  • 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.
  • BrowserRouter needs the server to fall back to index.html for every path, otherwise refreshing a nested route 404s. If you cannot configure the server, use HashRouter. This one comes up a lot.
  • Pair it with React.lazy to 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" />.