比较部分网址和一个变量

时间:2018-08-14 10:51:29

标签: javascript reactjs href

我想比较我的windows.location.href(网址)的一部分是否等于变量。

因此,我有一个名为ID的特定变量,它是一个常量,例如A,B,C,D ..现在,我的url为当前http://localhost:3000/section/A的格式,我想将A与A的ID,但我无法写逻辑。.请帮助!

我的react应用程序中有各个部分的导航。因此,单击“简介”(按ID = A分类)将href更改为http://localhost:3000/section/A,单击名为“背景”的第二部分(按ID = B分类)将href更改为http://localhost:3000/section/B

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

作为临时解决方法,这里是一个简单的解决方案

您可以使用/分割网址,以获取由/分隔的网址部分数组,然后获取该数组的最后一个元素

const lastPartOfUrl = window.location.href.split('/').pop()
if (lastPartOfUrl === ID) {
  // logic
}

enter image description here

更好的方法是使用React Router,以便您可以使用withRouter hoc为路由定义参数并在组件中获取参数值。 https://reacttraining.com/react-router/web/api/withRouter

您需要做的就是从react路由器中导入withRouter,然后用该函数包装您的组件。

withRouter(MyComponent)

然后您可以在道具中访问参数,例如:

const { match: { params } } = this.props

答案 2 :(得分:0)

如果该网址显示在您的地址栏中,则表示

var urlID = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)

是在URL中查找ID值的解决方案,您可以将其与您拥有的ID常量进行比较。

// For eaxmaple you could do something like...

switch (urlID) {
  case "A":
     // do something
  break;
  case "B":
     // do something
  break;

  // et cetera.

}

// or you could do something like...

if (ID === urlID) {
  // do something

}

相关问题