React-Router-4 如何检查手动输入的额外(不必要的)斜杠“/”?
How does React-Router-4 check for additional (unnecessary) slashes "/" typed in manually?
我在 React 路由器中发现了一个潜在的错误。在我的组件中,我这样做:
if(this.props.location.pathname === "/home")
检查用户是否在路径中。它可能有问题,因为如果用户手动输入 URL,则上述条件为 false
,例如 com/home/
如何处理这种情况?像这样进行多重检查是丑陋的:
if(this.props.location.pathname === "/home" || this.props.location.pathname === "/home/"))
关于如何以更好更简洁的方式执行此操作有什么建议吗?
您是否考虑过使用:
this.props.match.path
尝试
if (this.props.location.pathname.match(/^\/home\/?$/g))
这将完全匹配 /home
或 /home/
根据您想要实现的目标,您可以混合使用 exact
和 strict
属性。我建议调查一下 ;)
严格:布尔值
严格匹配;相当于Route.strict
.
// this will match both /home and /home/
<Route exact path="/foo" strict={false} component={foo} />
这里有 link 官方文档供以后参考。
您可以尝试使用 indexOf
:
if (this.props.location.indexOf("home") >= 1)
const URL = ["home", "/home", "/home/", "/home/about", "/about", "/logout", "/login/home"];
URL.forEach(url => {
const isMatch = url.indexOf("home") >= 1
console.log(`${url} is a match? ${isMatch}`);
})
注意事项(或好处)是它可以匹配任何包含 /home
的 URL 组合(如上所示)。
我在 React 路由器中发现了一个潜在的错误。在我的组件中,我这样做:
if(this.props.location.pathname === "/home")
检查用户是否在路径中。它可能有问题,因为如果用户手动输入 URL,则上述条件为 false
,例如 com/home/
如何处理这种情况?像这样进行多重检查是丑陋的:
if(this.props.location.pathname === "/home" || this.props.location.pathname === "/home/"))
关于如何以更好更简洁的方式执行此操作有什么建议吗?
您是否考虑过使用:
this.props.match.path
尝试
if (this.props.location.pathname.match(/^\/home\/?$/g))
这将完全匹配 /home
或 /home/
根据您想要实现的目标,您可以混合使用 exact
和 strict
属性。我建议调查一下 ;)
严格:布尔值
严格匹配;相当于Route.strict
.
// this will match both /home and /home/
<Route exact path="/foo" strict={false} component={foo} />
这里有 link 官方文档供以后参考。
您可以尝试使用 indexOf
:
if (this.props.location.indexOf("home") >= 1)
const URL = ["home", "/home", "/home/", "/home/about", "/about", "/logout", "/login/home"];
URL.forEach(url => {
const isMatch = url.indexOf("home") >= 1
console.log(`${url} is a match? ${isMatch}`);
})
注意事项(或好处)是它可以匹配任何包含 /home
的 URL 组合(如上所示)。