使用精确和严格的道具

Usage of exact and strict props

我正在 React-JS 中使用 React-Router:

<Route> 是一个内置组件,有两个不同的属性: exactstrict

问题

documentation 没有明确定义 exactstrict 之间的区别。

请帮助我。该文档在这一点上非常混乱且不清楚。

用例 1

如果您同时使用 exactstrict,那么 location.pathname 只会完全匹配路径属性中提供的内容。

示例:

<Route exact strict path="/one/" component={About}/>

只会匹配 /one/ 但不会匹配 /one/one/two.

用例 2

如果您只使用 strict,那么 location.pathname 将匹配带有尾部斜线的

示例:

<Route strict path="/one/" component={About}/>

将匹配 /one//one/two 但不匹配 /one

用例 3

如果您只使用 exact,那么 location.pathname 将匹配准确的位置路径。

示例:

<Route exact path="/one" component={About}/>

将匹配 /one/one/exact 道具不关心尾部斜杠。但它不会匹配 /one/two.

ReactRouter 的 strict 属性定义在路径名中是否存在请求路径的 strict 条目,如文档中所述。例如,如果您不想处理没有尾部斜线的页面路由,您的 Route 可以这样描述:

<Route path="/mypath/" strict ... />

所以路径名 /mypath 不会用这个 Route 处理,而路径名 /mypath/ 会。请注意,在这种模式下,此 Route 还将捕获其他子路由,例如/mypath/childroute/mypath/childroute/childroute2 等,但它不会捕获路由 /mypath?query=...。想想这个道具,就像你正在使用 "string".includes("substring"):

"/mypath".includes("/mypath/")       => false
"/mypath/".includes("/mypath/")      => true
"/mypath/kappa".includes("/mypath/") => true

exact 属性用于定义是否完全 请求的路径。 通常它用于包装没有子路由的路由(例如主页)。

<Route path="/" exact ... />
<Route path="/" ... />

第一条路线将只捕获 mydomain.commydomain.com/mydomain.com/?query=... 等路线。第二条路线将捕获所有路线,例如mydomain.commydomain.com/myroute.