有人可以解释一下
<Route exact path="/" component={Home} />
和
<Route path="/" component={Home} />
我不知道“确切”的意思
有人可以解释一下
<Route exact path="/" component={Home} />
和
<Route path="/" component={Home} />
我不知道“确切”的意思
Answers:
在这个例子中,什么都没有。exact当您具有多个具有相似名称的路径时,该参数将起作用:
例如,假设我们有一个Users显示用户列表的组件。我们还有一个CreateUser用于创建用户的组件。的网址CreateUsers应嵌套在下Users。因此,我们的设置可能如下所示:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
现在,这里的问题是,当我们转到http://app.com/users路由器时,将通过所有定义的路由,并返回它找到的第一个匹配项。因此,在这种情况下,它将首先找到Users路线,然后返回。都好。
但是,如果我们转到http://app.com/users/create,它将再次遍历所有定义的路线并返回找到的FIRST匹配项。React路由器会进行部分匹配,因此会/users部分匹配/users/create,因此它将再次错误地返回Users路由!
该exactPARAM禁用部分匹配的路由,并确保如果路径是精确匹配当前URL,它只是返回的路线。
所以在这种情况下,我们应该添加exact到我们的Users路由,这样只会匹配/users:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
exact我认为应该是默认设置
/admin//users在管理组件中以及/admin/users/create在根组件中),该怎么办?我目前exact遇到这种情况,典型的解决方案无法正常工作。
简而言之,如果您为应用程序的路由定义了多个路由,则用这样的Switch组件封装;
<Switch>
<Route exact path="/" component={Home} />
<Route path="/detail" component={Detail} />
<Route exact path="/functions" component={Functions} />
<Route path="/functions/:functionName" component={FunctionDetails} />
</Switch>
然后,您必须将exact关键字放入该路径的关键字,该路径的路径也包含在另一个路径的路径中。例如/,所有路径中都包含home路径,因此它需要具有exact关键字以将其与以开头的其他路径区分开/。原因也类似于/functions路径。如果要使用其他路径,例如/functions-detail或/functions/open-door其中包含/functions该路径,则需要使用exact该/functions路径。
在这里看看:https : //reacttraining.com/react-router/core/api/Route/exact-bool
确切:布尔
如果为true,则仅在路径location.pathname完全匹配时匹配。
**path** **location.pathname** **exact** **matches?**
/one /one/two true no
/one /one/two false yes
最短的答案是
请尝试这个。
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
exact属性/ prop 的含义,因此肯定不是“答案”。您应该尝试解决实际提出的问题,而不是为不确定OP实际存在的问题提供解决方案。