有人能解释一下两者的区别吗
<Route exact path="/" component={Home} />
and
<Route path="/" component={Home} />
我不知道确切是什么意思。
有人能解释一下两者的区别吗
<Route exact path="/" component={Home} />
and
<Route path="/" component={Home} />
我不知道确切是什么意思。
当前回答
请尝尝这个。
<Router>
<div>
<Route exact path="/" component={Home} />
<Route path="/news" component={NewsFeed} />
</div>
</Router>
其他回答
最简短的回答是
请尝尝这个。
<switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</switch>
看看这里:https://reacttraining.com/react-router/core/api/Route/exact-bool
准确:bool
当为true时,仅当路径与位置匹配时才匹配。路径名。
**path** **location.pathname** **exact** **matches?**
/one /one/two true no
/one /one/two false yes
通过使用exact,您可以确保主页组件的内容不会出现在其他页面上。
这是不使用exact的场景:
主页
地点:/
-----------------
homepage content
-----------------
第二个页面
地点:/第二页
-----------------
homepage content
-----------------
-----------------
second content
-----------------
==========================================
使用准确的:
主页
地点:/
-----------------
homepage content
-----------------
第二个页面
地点:/第二页
-----------------
second content
-----------------
如果你为你的应用程序的路由定义了多条路由,并包含了名称相似的routes组件,我们可能会遇到不可预测的行为。
例如:
<Routes>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Routes>
可能会导致一些错误
/users/create
因为一旦react找到一个与regex user*匹配的根,它就会将你重定向到/users路由
像这样使用exact
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
react - v6的新版本不再支持exact。
如他们的文件所述:
你不需要再使用一个精确的道具了。这是因为默认情况下所有路径都完全匹配。如果你想匹配更多的URL,因为你有子路由,请使用后面的*,如<Route path="users/*">
请尝尝这个。
<Router>
<div>
<Route exact path="/" component={Home} />
<Route path="/news" component={NewsFeed} />
</div>
</Router>