# React Router 路由导航hooks使用总结

1. 核心组件

1.1 BrowserRouter

BrowserRouter 是 React Router 应用的基础容器,使用 HTML5 的 history API 实现路由功能。

jsx 复制代码
import { BrowserRouter } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <div>
        {/* 你的应用组件 */}
      </div>
    </BrowserRouter>
  );
}

1.2 HashRouter

HashRouter 使用 URL 的 hash 部分(#)来保持 UI 与 URL 同步,适用于不支持 HTML5 history API 的旧版浏览器。

jsx 复制代码
import { HashRouter } from 'react-router-dom';

function App() {
  return (
    <HashRouter>
      <div>
        {/* 你的应用组件 */}
      </div>
    </HashRouter>
  );
}

1.3 Routes 和 Route

RoutesRoute 组件用于定义应用的路由结构。

jsx 复制代码
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="/users/:id" element={<UserProfile />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

Link 组件用于创建导航链接,它渲染为 HTML 的 <a> 标签,但不会触发页面刷新。

jsx 复制代码
import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <Link to="/">首页</Link>
      <Link to="/about">关于</Link>
      <Link to="/users/123" state={{ from: 'navigation' }}>用户详情</Link>
      <Link to="/search?q=react">搜索</Link>
    </nav>
  );
}

NavLinkLink 的特殊版本,可以根据当前路由状态添加样式。

jsx 复制代码
import { NavLink } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <NavLink 
        to="/"
        className={({ isActive }) => isActive ? 'active' : ''}
      >
        首页
      </NavLink>
      <NavLink 
        to="/about"
        style={({ isActive }) => ({
          color: isActive ? '#007bff' : '#000'
        })}
      >
        关于
      </NavLink>
    </nav>
  );
}

Navigate 组件用于执行编程式导航,通常用于重定向场景。

jsx 复制代码
import { Navigate } from 'react-router-dom';

function PrivateRoute({ children }) {
  const isAuthenticated = checkAuth();
  
  if (!isAuthenticated) {
    return <Navigate to="/login" replace state={{ from: location.pathname }} />;
  }
  
  return children;
}

1.7 Outlet

Outlet 组件用在父路由中,渲染当前匹配的子路由。

jsx 复制代码
import { Outlet } from 'react-router-dom';

function Layout() {
  return (
    <div>
      <header>
        <nav>{/* 导航内容 */}</nav>
      </header>
      
      <main>
        <Outlet /> {/* 子路由将在这里渲染 */}
      </main>
      
      <footer>{/* 页脚内容 */}</footer>
    </div>
  );
}

2. 路由 Hooks

2.1 useRoutes

useRoutes hook 用于配置式路由,可以用对象的方式定义路由结构。

jsx 复制代码
import { useRoutes } from 'react-router-dom';

function App() {
  const routes = useRoutes([
    {
      path: '/',
      element: <Layout />,
      children: [
        { path: '', element: <Home /> },
        { path: 'about', element: <About /> },
        { path: 'users/:id', element: <UserProfile /> }
      ]
    }
  ]);
  
  return routes;
}

2.2 useNavigate

useNavigate hook 提供编程式导航能力。

jsx 复制代码
import { useNavigate } from 'react-router-dom';

function NavigationButtons() {
  const navigate = useNavigate();
  
  return (
    <div>
      <button onClick={() => navigate('/home')}>首页</button>
      <button onClick={() => navigate(-1)}>返回</button>
      <button onClick={() => navigate('/user/123', { 
        state: { from: 'button' }
      })}>用户详情</button>
    </div>
  );
}

2.3 useParams

useParams hook 用于获取 URL 参数。

jsx 复制代码
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams();
  
  return (
    <div>
      <h2>用户 ID: {id}</h2>
      {/* 使用 id 获取用户数据 */}
    </div>
  );
}

2.4 useSearchParams

useSearchParams hook 用于读取和修改 URL 的查询参数。

jsx 复制代码
import { useSearchParams } from 'react-router-dom';

function SearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const query = searchParams.get('q') || '';
  
  return (
    <div>
      <input
        value={query}
        onChange={(e) => setSearchParams({ q: e.target.value })}
        placeholder="搜索..."
      />
      <p>搜索关键词: {query}</p>
    </div>
  );
}

2.5 useLocation

useLocation hook 返回当前路由的位置信息。

jsx 复制代码
import { useLocation } from 'react-router-dom';

function LocationInfo() {
  const location = useLocation();
  
  return (
    <div>
      <p>当前路径: {location.pathname}</p>
      <p>查询参数: {location.search}</p>
      <p>状态数据: {JSON.stringify(location.state)}</p>
    </div>
  );
}

2.6 useMatch

useMatch hook 用于匹配当前 URL 是否符合指定的路径模式。

jsx 复制代码
import { useMatch } from 'react-router-dom';

function MatchExample() {
  const match = useMatch('/users/:id');
  
  if (match) {
    return <p>匹配到用户路由,ID: {match.params.id}</p>;
  }
  
  return <p>未匹配到用户路由</p>;
}

2.7 useInRouterContext

useInRouterContext hook 用于检查组件是否在 Router 上下文中渲染。

jsx 复制代码
import { useInRouterContext } from 'react-router-dom';

function RouterContextChecker() {
  const inRouterContext = useInRouterContext();
  
  return (
    <div>
      {inRouterContext ? 
        '组件在 Router 内部渲染' : 
        '组件在 Router 外部渲染'}
    </div>
  );
}

2.8 useNavigationType

useNavigationType hook 返回当前导航的类型(POP、PUSH 或 REPLACE)。

jsx 复制代码
import { useNavigationType } from 'react-router-dom';

function NavigationTypeInfo() {
  const navigationType = useNavigationType();
  
  return <div>导航类型: {navigationType}</div>;
}

2.9 useOutlet

useOutlet hook 返回当前匹配的子路由元素。

jsx 复制代码
import { useOutlet } from 'react-router-dom';

function Layout() {
  const outlet = useOutlet();
  
  return (
    <div>
      {outlet || <div>没有匹配的子路由</div>}
    </div>
  );
}

2.10 useResolvedPath

useResolvedPath hook 将相对路径解析为绝对路径。

jsx 复制代码
import { useResolvedPath } from 'react-router-dom';

function PathResolver() {
  const resolvedPath = useResolvedPath("../about");
  
  return <div>解析后的路径: {resolvedPath.pathname}</div>;
}
相关推荐
万少2 分钟前
万少用9个AI工具,帮朋友完成了一个"不可能"的项目
前端
小小小小宇4 分钟前
Vue `import` 为什么可以异步加载
前端
WMYeah9 分钟前
【无标题】
前端·rust·抽奖程序·跨平台抽奖程序
Unbelievabletobe10 分钟前
免费外汇api的响应时间在不同时段下的波动分析
大数据·开发语言·前端·python
大哥,带带弟弟19 分钟前
Grafana 前端嵌入与 JWT 鉴权实战
前端·grafana
小小小小宇20 分钟前
前端 V8 引擎垃圾回收机制与内存问题排查
前端
前端老石人31 分钟前
CSS 值定义语法
前端·css
sheeta199841 分钟前
Vue 前端基础笔记
前端·vue.js·笔记
小小小小宇42 分钟前
GitLab + GitLab Runner + Qiankun 微前端 + Nginx + Node 中间件 前端开发机从零搭建 CI/CD 全流程
前端
前端那点事1 小时前
别再写垃圾组件!Vue3 如何设计「真正可复用」的高质量通用组件
前端·vue.js