如果我有这样的东西:
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
我的路线配置如下:
export default [{
path: '/',
exact: true,
main: Home
},
{
path: '/:someId',
exact: true,
main: Profile
},
{
path: '*',
main: NotFound
}];
其中应用程序只是路由和其他组件的包装,例如:
class App extends Component {
render() {
return (
<div>
<Header />
<Switch>
{routes.map((route, i) => <Route exact key={i} component={route.main} path={route.path}/>)}
</Switch>
<AnotherComponent {...this.props} />
</div>
);
}
}
有没有办法让 AnotherComponent 使用 match.params 或公开它们?我已经尝试使用 withRouter 包装组件,并将其添加为没有路径匹配的路由,例如:
<Route component={AnotherComponent} />
当路由为/:someId 时,它会渲染 Profile 和 AnotherComponent,但 AnotherComponent 的 match.params 为空:/。
这可能吗? 谢谢!
请您参考如下方法:
编辑:您可以使用https://v5.reactrouter.com/web/api/Hooks/useroutematch这些天直接。
原始答案
您可以使用matchPath
import { matchPath } from 'react-router'
import { useLocation } from 'react-router-dom'
//----
const { pathname } = useLocation()
const params = matchPath(pathname, { path:"/:someId" })
//----






