React : <Route exact path="/" /> 和 <Route path="/" /> 的区别

新手上路,请多包涵

有人可以解释两者之间的区别吗

<Route exact path="/" component={Home} />

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

我不知道 exact 的含义。

原文由 batt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

在这个例子中,什么都没有。当您有多个具有相似名称的路径时, exact 参数会起作用:

例如,假设我们有一个显示用户列表的 Users 组件。我们还有一个 CreateUser 用于创建用户的组件。 CreateUsers 的 url 应该嵌套在 Users 下。所以我们的设置可能看起来像这样:

 <Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

现在问题出在这里,当我们转到 http://app.com/users 路由器将遍历我们定义的所有路由并返回它找到的第一个匹配项。所以在这种情况下,它会先找到 Users 路由,然后返回它。都好。

但是,如果我们去 http://app.com/users/create ,它将再次遍历我们定义的所有路由并返回它找到的第一个匹配项。 React 路由器进行部分匹配,所以 /users 部分匹配 /users/create ,所以它会再次错误地返回 Users 路由!

exact 参数禁用路由的部分匹配,并确保仅在路径与当前 url 完全匹配时才返回路由。

所以在这种情况下,我们应该将 exact 添加到我们的 Users 路由中,这样它就只会匹配 /users

 <Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

文档详细解释了 exact 并给出了其他示例。

原文由 Chase DeAnda 发布,翻译遵循 CC BY-SA 4.0 许可协议

简而言之,如果您为应用程序的路由定义了多个路由,并包含在 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 路径。 If you want to use another route path like /functions-detail or /functions/open-door which includes /functions in it then you need to use exact for the /functions 路线。

原文由 milkersarac 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进