检查反应路由器路径是否处于活动状态 [英] Check if react-router path is active
问题描述
如何检查通用的 react-router 路径是否匹配当前位置路径名?
How to check if generic react-router path matches current location pathname?
react-router path: /Movies/:id
location.pathname: /Movies/56fa7446bae6eb301e5937f3
我想使用带有菜单按钮的路由路径来设置 class="active".
I want to use route paths with menu buttons, to set class="active".
澄清一下,我的应用程序中的路径如下所示:
To clarify, paths in my app look like:
/Movies/56fa7/watch
而不喜欢:
/Movies/watch/56fa7
如何查看之前的路由是否有效?
How do I check if the former route is active?
没有 组件是否可行?
Is it doable without <Link>
component?
/Movies/56fa7/watch
在/Movies
之后是任意的,而显然不能指向任意地点.所以让我们暂时忽略
:
/Movies/56fa7/watch
is arbitrary after /Movies
, and <Link>
obviously can't be pointed to an arbitrary location. So let's ignore <Link>
for a moment:
react-router 中是否有独立的函数或属性来检查 /Movies/:id/watch
是否处于活动状态?
Is there a standalone function or property in react-router that checks if /Movies/:id/watch
is active?
推荐答案
根据 docs,你可以使用 matchPath
函数接受两个参数:
According to the docs, you could use matchPath
function which takes two arguments:
- 路径名要匹配(
String
). - 选项(
Object
)或路径(String
)来匹配.
- pathname you want to match (
String
). - options (
Object
) or path (String
) to match against.
如果匹配,它将返回此形状的对象:
If matched it will return an object of this shape:
{
path, // the path used to match
url, // the matched portion of the URL
isExact, // whether or not we matched exactly
params
}
否则你会得到 null
.
要在您的组件中使用它,您只需执行以下操作:
To make use of it in your components you could simply do:
import { matchPath } from 'react-router';
// ...
render () {
const isMovieWatchPathActive = !!matchPath(
this.props.location.pathname,
'/Movies/:id/watch'
);
// ...
}
希望对大家有所帮助.
这篇关于检查反应路由器路径是否处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!