如果您的应用程序中有可以更改的 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/