反应:<路由精确路径=“/"之间的区别/>和 <Route path="/";/> [英] React : difference between <Route exact path="/" /> and <Route path="/" />
问题描述
谁能解释一下
<Route exact path="/" component={Home} />
和
<Route path="/" component={Home} />
我不知道精确"是什么意思
I don't know the meaning of 'exact'
推荐答案
在这个例子中,什么都没有.当您有多个具有相似名称的路径时,exact
参数就会发挥作用:
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
例如,假设我们有一个显示用户列表的 Users
组件.我们还有一个用于创建用户的 CreateUser
组件.CreateUsers
的 url 应该嵌套在 Users
下.所以我们的设置看起来像这样:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
现在的问题是,当我们转到 http://app.com/users
时,路由器将遍历我们定义的所有路由并返回它找到的第一个匹配项.所以在这种情况下,它会先找到 Users
路由,然后返回它.一切都很好.
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
但是,如果我们访问 http://app.com/users/create
,它将再次通过我们定义的所有路由并返回它找到的第一个匹配项.React 路由器做部分匹配,所以 /users
部分匹配 /users/create
,所以它会再次错误地返回 Users
路由!
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
exact
参数禁用路由的部分匹配,并确保仅在路径与当前 url 完全匹配时才返回路由.
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
因此,在这种情况下,我们应该将 exact
添加到我们的 Users
路由中,以便它仅匹配 /users
:
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
The docs explain exact
in detail and give other examples.
这篇关于反应:<路由精确路径=“/"之间的区别/>和 <Route path="/";/>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!