react 路由写法

101 阅读1分钟

在使用 React Router 时,路径(path)是否需要加 / 取决于具体的情况和你希望实现的路由结构。以下是一些常见的情况和建议:

1. 根路径

对于根路径,通常需要加 /

<Route path="/" component={Home} />

2. 子路径

对于子路径,可以选择加 / 或不加 /,但通常建议加上 / 以保持一致性和清晰性:

<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />

3. 嵌套路由

(绝对路由)在嵌套路由中,子路径通常也需要加 /,以确保路径的正确解析:

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

嵌套路由的第二种写法

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

(相对路由)在这种情况下,profilesettings 是**相对于 **/dashboard 的路径,最终的 URL 会是 /dashboard/profile/dashboard/settings

4. 动态路径

对于动态路径参数,也建议加 /

<Route path="/user/:id" component={User} />

5. 相对路径

在某些情况下,你可能会使用相对路径。在这种情况下,不加 / 也是可以的,但需要确保路径的正确性:

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

总结

虽然在某些情况下不加 / 也是可以的,但为了保持代码的一致性和可读性,通常建议在路径前加上 /。这有助于避免路径解析问题,并使代码更易于维护和理解。