使用精确和严格的props

IT技术 reactjs react-router react-router-dom
2021-05-22 11:57:09

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

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

问题

文档没有明确定义exact之间的区别strict

请帮助我。该文件非常混乱,当时不清楚。

2个回答

用例 1

如果您一起使用exactand strict,那么location.pathname将仅与路径props中提供的完全匹配。

例子:

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

只会匹配/one/而不匹配/oneand /one/two

用例 2

如果仅使用strictlocation.pathname则将匹配尾随斜线。

例子:

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

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

用例 3

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

例子:

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

将匹配/one/one/exactprops不关心斜线。但它不会匹配/one/two

ReactRouter 的strictprop 定义路径名中是否有严格的请求路径条目,如文档中所述。例如,如果您不希望在没有尾部斜杠的情况下处理页面的路由,您Route可以这样描述:

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

所以路径名/mypath不会用 this 处理,Route路径/mypath/名将是。注意,在这种模式下这Route也将赶上其他孩子的路由,例如/mypath/childroute/mypath/childroute/childroute2等等,但它不会赶上路线/mypath?query=...想想这个props,就像你正在使用"string".includes("substring")

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

exactprops是用来定义如果有确切的请求的路径。通常它用于包装没有子路由的路由(例如主页)。

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

第一条路线会赶上像只路线mydomain.commydomain.com/mydomain.com/?query=...等第二个将捕获的所有途径,例如两者的mydomain.commydomain.com/myroute