繁体   English   中英

如何用 React-Router 中的历史记录替换链接组件行为

[英]How to replace Link component behavior with History in React-Router

在我的应用程序中,我有

    <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的类似 Tab 的组件,它使用Link重定向到子患者路线。

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

此时一切正常。 然而,我的RouteTab组件具有响应行为,当移动时它使用 Select 来显示项目菜单。 为了模拟链接行为,我正在使用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

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

这是我从沙盒中提取的一个工作示例: https://codesandbox.io/s/patient-care-router-2m3oh

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM