bat*_*att 91 reactjs react-router react-router-dom
有人可以解释之间的区别
<Route exact path="/" component={Home} />
Run Code Online (Sandbox Code Playgroud)
和
<Route path="/" component={Home} />
Run Code Online (Sandbox Code Playgroud)
我不知道'确切'的含义
Cha*_*nda 168
在这个例子中,没有什么.exact当您有多个具有相似名称的路径时,param会起作用:
例如,假设我们有一个Users显示用户列表的组件.我们还有一个CreateUser用于创建用户的组件.url CreateUsers应该嵌套在Users.所以我们的设置看起来像这样:
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
Run Code Online (Sandbox Code Playgroud)
现在这里的问题,当我们去http://app.com/users路由器时将经历我们所有已定义的路由并返回它找到的FIRST匹配.所以在这种情况下,它会Users首先找到路径,然后返回它.都好.
但是,如果我们去了http://app.com/users/create,它将再次通过我们所有已定义的路线并返回它找到的FIRST匹配.React路由器进行部分匹配,因此/users部分匹配/users/create,因此会Users再次错误地返回路由!
该exactPARAM禁用路由部分匹配,并确保如果路径是精确匹配当前URL,它只是返回的路线.
所以在这种情况下,我们应该添加exact到我们的Users路线,以便它只匹配/users:
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
Run Code Online (Sandbox Code Playgroud)
mil*_*rac 21
简而言之,如果您为应用程序的路由定义了多个路由,则用这样的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>
Run Code Online (Sandbox Code Playgroud)
然后,您必须将exact关键字放在Route 中,它的路径也包含在另一个 Route 的路径中。例如主路径/包含在所有路径中,因此它需要有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
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您为应用程序的路由定义了多个路由,并且包含具有相似名称的路由组件,我们可能会得到不可预测的行为。
例如:
<Routes>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Routes>
Run Code Online (Sandbox Code Playgroud)
当您转到路线时可能会出现一些错误
/users/create
Run Code Online (Sandbox Code Playgroud)
因为一旦 React 找到与正则表达式 user* 匹配的根目录,它就会将您重定向到 /users 路由
使用完全像这样
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
新版本的react-v6不再支持exact。
正如他们的文档中所述:
您不再需要使用精确的道具。这是因为默认情况下所有路径都完全匹配。如果您想匹配更多的 URL,因为您有子路由,请使用尾随 *,如下所示
<Route path="users/*">
| 归档时间: |
|
| 查看次数: |
45142 次 |
| 最近记录: |