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

火山引擎 最新活动