博主头像
<CodeEra />

心存敬畏 行有所止

React 路由匹配规则与Redirect使用

一、React 路由匹配规则

在 React 中,路由匹配是通过 react-router-dom 库实现的。以下是常见的路由匹配规则:

  1. 精确匹配 (exact)

    • 使用 exact 属性可以确保路由路径完全匹配时才渲染组件。
    • 例如:<Route exact path="/" component={Home} />
    • 如果不加 exact/about 也会匹配到 /
  2. 路径参数 (:param)

    • 使用 :param 可以动态匹配路径中的参数。
    • 例如:<Route path="/user/:id" component={User} />
    • 在组件中可以通过 useParams() 获取参数值。
  3. 可选路径 (?)

    • 使用 ? 表示路径参数是可选的。
    • 例如:<Route path="/search/:query?" component={Search} />
    • /search/search/react 都会匹配。
  4. 通配符 (*)

    • 使用 * 可以匹配任意路径。
    • 例如:<Route path="/docs/*" component={Docs} />
    • /docs/getting-started/docs/api 都会匹配。
  5. 嵌套路由

    • 在父组件中定义子路由,实现嵌套路由。
    • 例如:

      <Route path="/dashboard" component={Dashboard}>
        <Route path="/dashboard/profile" component={Profile} />
        <Route path="/dashboard/settings" component={Settings} />
      </Route>

二、Redirect 的使用

Redirect 用于在路由匹配时重定向到另一个路径。以下是常见用法:

  1. 基本重定向

    • 使用 Redirect 组件实现重定向。
    • 例如:

      <Route path="/old-path">
        <Redirect to="/new-path" />
      </Route>
  2. 条件重定向

    • 结合逻辑判断实现条件重定向。
    • 例如:

      {isLoggedIn ? <Redirect to="/dashboard" /> : <Login />}
  3. 保留查询参数

    • 使用 to 对象的 search 属性保留查询参数。
    • 例如:

      <Redirect to={{ pathname: "/new-path", search: location.search }} />
  4. Switch 中使用

    • Switch 中使用 Redirect 作为默认路由。
    • 例如:

      <Switch>
        <Route path="/home" component={Home} />
        <Route path="/about" component={About} />
        <Redirect to="/home" />
      </Switch>

三、注意事项

  1. Redirect 会替换历史记录

    • 默认情况下,Redirect 会替换当前的历史记录。如果需要添加新记录,可以使用 push 属性:

      <Redirect to="/new-path" push />
  2. 路由匹配顺序

    • Switch 中,路由按从上到下的顺序匹配,第一个匹配的路由会被渲染。
  3. 避免循环重定向

    • 确保重定向逻辑不会导致无限循环。例如:

      <Route path="/a">
        <Redirect to="/b" />
      </Route>
      <Route path="/b">
        <Redirect to="/a" />
      </Route>

四、总结

  • 掌握 React 路由的匹配规则(exact、路径参数、通配符等)是构建动态路由的基础。
  • Redirect 是实现页面跳转和条件导航的重要工具,需注意避免循环重定向。
  • 结合 Switch 和嵌套路由,可以构建复杂的路由结构。
发表新评论