17

如果我有这样的事情:

<ConnectedRouter history={history}>
    <App />
</ConnectedRouter>

我的路线配置如下所示:

export default [{
    path: '/',
    exact: true,
    main: Home
}, 
{
    path: '/:someId',
    exact: true,
    main: Profile
},
{
    path: '*',
    main: NotFound
}];

其中 app 只是路由和其他组件的包装器,例如:

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,例如:

<Route component={AnotherComponent} />

当路由为 /:someId 时,它会同时渲染 Profile 和 AnotherComponent,但 AnotherComponent 的 match.params 为空:/。

这可能吗?谢谢!

4

3 回答 3

5

编辑:这些天您可以直接使用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" })
 //----

于 2021-05-21T13:58:45.760 回答
2

如果您在 Route 上有路径,React 路由器只会返回参数。您可以从顶层传递参数。让该组件在其中渲染。它将有权访问参数。至于任何其他时间,您需要这样做:

<Route  path="/:someId" component={AnotherComponent} />

如果你想让它真正得到那个参数!

只有组件下方的子项Route才能访问参数。您应该以只有该路由内的组件需要其参数的方式构建您的应用程序。

于 2017-06-27T14:27:51.780 回答
0

您可以使用它自己的 Route 组件包装该组件,如下所示:

...  
<Route path="/cameras/:camera/">
  <CameraName />
</Route>
...

// this is so the camera name can be fetched from the route.
const CameraName = () => {
  let { camera } = useParams();
  return <div>{camera}</div>;
};
于 2021-10-21T03:28:44.460 回答