javascript - this.props.location.pathname 用于 React 中的动态 URL

标签 javascript reactjs react-router

如果您的应用程序中有可以更改的 URL(例如 /profile/1/profile/2,您如何从 this. props.location.pathname?

在我的 Profile 组件中,我有一个 componentDidMount 方法,如下所示:

componentDidMount () {
    if (this.props.location.pathname === 'profile/:id/') {
      console.log('is profile')
  } else {
      console.log('is not profile')
  }
}

当我在个人资料页面时返回 不是个人资料

我正在使用的项目使用 react-redux-starter-kit作为基础(不确定是否有帮助),它使用 react-router-v3。

最佳答案

你可以试试这个

import { matchPath } from 'react-router-dom';

if (matchPath(this.props.location.pathname, { path: 'profile/:id' })) {}

或者

this.props.match.path === 'profile/:id'

我不确定如果您的 Profile 组件不是配置文件,为什么它会被挂载。

关于javascript - this.props.location.pathname 用于 React 中的动态 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964925/

相关文章:

javascript - 从组件访问 Vuex Store 中的 Mutator 会产生未知突变类型错误

javascript - 使用 iframe 嵌入 iPhone YouTube

javascript - this.props.getItemCount 不是函数(VirtualizedList、React Native)

javascript - 无法在 react 中将 Prop 传递给子组件

javascript - react - react 路由器 - privateRoute - 无限循环

javascript - 在 React 中使用 Dygraph 和 redux?

javascript - 单击 iframe 按钮关闭父窗口

javascript - React-router-dom (v6) 和 Framer Motion (v4)

reactjs - 我如何使用导航将 Prop 传递到下一个屏幕

javascript - 使用 underscore.js 可以减少返回数组?