如何用React-Router中的History替换Link组件的行为

问题描述 投票:0回答:1

在我的应用中,我有

    <Switch>
        <Route path="/" component={DashboardRoute} exact={true} />
        <Route path="/patients/:id" component={PatientRoute} />
        <Redirect to='/' />
      </Switch>

然后在PatientRoute内部,我还有另一个具有动态路由的Switch。

<Switch >
  {panes.map(pane => {
     return <Route path={`/patients/:id/${pane.to}`}>
        {pane.render()}
     </Route>
  })}
</Switch>

我已经建立了一个名为RouteTab的选项卡,该组件使用Link重定向到亚患者路线。

<div className="TabButtons">
  {panes.map((p, index) => <Link key={p.to} to={p.to} label={p.menuItem}/>)}
</div>

此时一切正常。但是,我的RouteTab组件具有响应行为,当使用Mobile时,它使用Select来显示项目菜单。为了模拟Link行为,我正在使用history.push,URL会更改,但页面不会重新呈现。

<Select
   value={panes[activeTab].menuItem}
   onChange={(e, data) => {
      const value = data.value;
      const newTabIndex = panes.findIndex(p => p.menuItem === value)
      const newTab = panes[newTabIndex]

      history.replace(newTab.to) //<--- Here
   }}
   options={panes.map(p => ({
      key: p.menuItem,
      value: p.menuItem,
      text: p.menuItem,
   }))}></Select>

这里是一个完整的示例https://codesandbox.io/s/patient-care-router-45t5w

javascript reactjs react-router browser-history
1个回答
1
投票

您在routeTab中不需要另一个<Router>。这样做似乎会创建两个不同的路由器实例,这就是history.push无法正常工作的原因。

这是我从沙箱中派生的工作示例:https://codesandbox.io/s/patient-care-router-2m3oh

我禁用了在同一视图中测试下拉菜单的响应能力。

我从这里的文档中的这个示例中得到的想法:https://reacttraining.com/react-router/web/example/modal-gallery

© www.soinside.com 2019 - 2024. All rights reserved.