【问题标题】:Is there a way to expose route params outside <Route> component?有没有办法在 <Route> 组件之外公开路由参数?
【发布时间】:2025-12-07 03:40:01
【问题描述】:

如果我有这样的事情:

<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 component={AnotherComponent} />

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

这可能吗? 谢谢!

【问题讨论】:

    标签: javascript reactjs react-router-redux react-router-v4 react-router-dom


    【解决方案1】:

    您可以像这样用它自己的 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>;
    };
    

    【讨论】:

      【解决方案2】:

      您可以使用matchPath

      import { matchPath } from 'react-router'
      import { useLocation } from 'react-router-dom'
      
       //----
      const { pathname } = useLocation()
      
      const params =  matchPath(pathname, { path:"/:someId" })
       //----
      
      

      【讨论】:

        【解决方案3】:

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

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

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

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

        【讨论】:

        • 我明白,问题是我需要这个组件始终存在。起初是“隐藏的”,但是当导航到 /:someId 时,我需要使用此 id 的信息对其进行初始化,然后让它在整个应用程序中主动显示,即使路线发生变化。
        • 然后在最后用问号渲染它:) &lt;Route path="/:someId?" component={AnotherComponent} /&gt; 这将渲染它有或没有那个id!
        • 完美!谢谢!