Skip to content

React Router

客户端-边 routing 使用 React Router, route 定义, 导航, and URL 参数.

你将学到

  • 设置 React Router 使用 Routes and Route
  • 导航使用链接 and useNavigate
  • 读取 URL 参数使用 useParams
  • Nested routes and 布局 routes

概念讲解

What Is React Router?

React Router is the standard library for client-side routing in React applications. It lets you map URL paths to components, so different URLs render different pages without a full page reload. This creates a single-page application (SPA) experience where navigation feels instant. React Router v6 (and the newer v7) introduced a data-loading API and simplified the route definition syntax.

Defining Routes

You wrap your application in a <BrowserRouter> and define routes with <Routes> and <Route>. Each <Route> has a path and an 元素 prop. React Router matches the current URL against the route paths and renders the matching element. Routes can be nested — a parent route renders an <Outlet /> where child routes appear. This lets you share layouts (headers, sidebars) across multiple pages.

Navigation

Use the <链接> component for navigation — it renders an <> tag but intercepts the click to do client-side routing without a full reload. For programmatic navigation (after a form submit, for example), use the useNavigate() hook to get a 导航 function. You can pass state through navigation: 导航("/dashboard", { 状态: { fromLogin: 真 } }) and read it with useLocation().状态.

URL Parameters

Dynamic route segments are defined with a colon: <Route path="/用户/:id" 元素={<UserProfile />} />. Inside the component, useParams() returns { id: "123" }. Query parameters are accessed via useSearchParams(), which returns a URLSearchParams instance you can read and update. URL parameters are the primary way to make your app's state shareable and bookmarkable.

Navigation Guards and Loaders

React Router v6.4+ introduced data APIs: loader functions fetch data before a route renders, and 操作 functions handle form submissions. These replace the need for useEffect-based fetching in route components. Navigation guards can be implemented with the useBlocker hook (in newer versions) or by checking conditions in loaders. These APIs bring React Router closer to framework-level routing like Next.js.

示例代码

              import { BrowserRouter, Routes, Route, Link, useParams, Outlet } from "react-router-dom";

function Layout() {
  return (
    <div>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/users">Users</Link>
      </nav>
      <Outlet /> {/* Child routes render here */}
    </div>
  );
}

function UserProfile() {
  const { id } = useParams(); // Read the :id URL parameter.
  return <h1>User Profile for ID: {id}</h1>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<h1>Home Page</h1>} />
          <Route path="users" element={<h1>All Users</h1>} />
          <Route path="users/:id" element={<UserProfile />} />
          <Route path="*" element={<h1>404 Not Found</h1>} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
            

BrowserRouter wraps app. 布局渲染 shared nav 使用 Outlet for child routes. UserProfile 读取 :id param. * route catches unmatched URLs.

动手试一试

  • Regex Tester

    测试 regex 模式 for 验证 route paths and URL 参数.

  • JSON Formatter

    格式 route 配置对象当 构建动态 routes.

常见错误

错误写法

Using <> 标签相反的 <链接> for 内部导航

正确做法

Regular <> 标签 cause 完整 page reload, losing 客户端状态. Use <链接到="/path"> for 内部导航. Use <> 仅 for 外部链接.

错误写法

Forgetting 到 wrap app in BrowserRouter

正确做法

Router Hook 如 useNavigate and useParams 仅工作内部 Router 上下文. Wrap 你的 app (or routing 部分) in <BrowserRouter> at 顶部 level.

练习 React Router

6 个练习

练习 React Router

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误