You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中<Route exact path="/" />与<Route path="/" />的区别及exact含义

Difference Between <Route exact path="/" /> and <Route path="/" /> in React Router

Hey folks! Let's clear up the confusion around these two Route configurations and what the exact attribute actually does.

Without the exact attribute (<Route path="/" />)

When you omit exact, React Router uses prefix matching—meaning it will match any URL that starts with the path you've defined.

For example, if you have these routes:

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

Visiting /about will render both the Home and About components. Why? Because /about starts with /, so the first Route's path condition is satisfied along with the second one. This is almost never what you want for your root route!

With the exact attribute (<Route exact path="/" />)

Adding exact switches the matching behavior to exact match mode. Now the Route will only render its component if the current URL's path is a perfect, character-for-character match with the path value.

Using the same example but with exact:

<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
  • Visiting / will only render the Home component.
  • Visiting /about will only render the About component.

What exact actually means

exact is a boolean prop that defaults to false. When set to true, it tells React Router to skip its default prefix matching logic and only consider the Route a match if the entire URL path matches the path prop exactly.

This is critical for root routes (like /) because almost every other route in your app will start with /—without exact, your root component would show up on every page.

内容的提问来源于stack exchange,提问作者batt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:51:20