问题描述
在React Router文档中在此处说:
In the react router docs here it says:
<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>
它们如何与路径/about
匹配?除非用户具有用户名 about
,否则我看不出为什么会如此.我想念什么?
How do they all match the path /about
? I can't see why this would be true, unless a user had the username about
. What am I missing?
推荐答案
The Line
<Route path="/:user" component={User}/>
表示/
之后的所有内容都将传递到 component
和 User 代码>组件将被渲染.
means that everything after /
will be passed into this.props.params.user
variable of component
and User
component would be rendered.
匹配规则仅关心是否给定的 path
与您的 path =
模式匹配,并不关心资源是否实际存在.如果我得到以/
开头的路径,并且变量后面有文本,则该文本将被解析为Route Parameter user
和 User
组件将被渲染,就是这样.因此,是的,在这种情况下, this.props.params.user
的值将为"about",但是如何处理变量以及在找不到该名称的情况下显示的内容完全可以使用给你.
The matching rule only cares if the path
given matches your path=
pattern, it doesn't care if the resource actually exists. If I get path starting with /
the and there is a text following the variable, the text will be parsed as Route Parameter user
and User
component will be rendered and that's it. So yes, this.props.params.user
will have value of "about" in this case, but how you handle the variable and what would you display in case user such name is not found is entirely up to you.
我认为他们只是想说,如果您有更多通常可以一次全部匹配的模式,则应使用< Switch>
组件,这样实际上只有第一个匹配渲染.
I think they are just trying to say that in case that you have more patterns that would normally get matched all at once, you should use <Switch>
component so only the first match would actually render.
例如使用时< Switch>
:
A),路径为/about
,规则
<Route path="/about" component={About}/>
将被匹配, About
组件将被渲染,并且不再进行评估.
would get matched and About
component would get rendered and no more evaluation are done.
B)如果路径为/something
,则规则
<Route path="/about" component={About}/>
不会被匹配,但是规则:
won't get matched, but rule:
<Route path="/:user" component={User}/>
将被匹配,并且 User
组件将以 something
作为 this.props.params.user
param呈现,并且不再进行评估完成.
would get matched, and User
component would be rendered with something
as this.props.params.user
param and no more evaluation are done.
C)如果路径为/
规则
<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
无法匹配,但
<Route component={NoMatch}/>
will和 NoMatch
组件将被渲染.
will and NoMatch
component would get rendered.
相反,当不使用 < Switch>
时,如果您的路径是/关于
:
On contrary when not using <Switch>
, if your path is /about
:
<Route path="/about" component={About}/>
将得到匹配,因为此规则将匹配路径等于/about
的所有路由.
Would get matched, because this rule matches all routes which paths are equal to /about
.
<Route path="/:user" component={User}/>
也将被匹配,因为此规则匹配所有以/
开头的路由,并且后面有一个文本.
Would also get matched because this rule matches all routes which start with /
and there is a text following.
<Route component={NoMatch}/>
也将被匹配,因为该规则根本不关心路径,它总是被匹配.
Would too get matched because this rule doesn't care about path at all, it gets always matched.
这篇关于反应路由器交换机组件匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!