简体   繁体   English

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

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

In my app I have在我的应用程序中,我有

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

Then inside PatientRoute I have another Switch with dynamic routes.然后在PatientRoute内部,我有另一个带有动态路由的 Switch。

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

I've built a Tab like component called RouteTab that uses Link to redirect to a sub patient route.我构建了一个名为RouteTab的类似 Tab 的组件,它使用Link重定向到子患者路线。

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

At this point everthing works fine.此时一切正常。 However My RouteTab components has a responsive behavior, when Mobile it uses a Select to display the menu of items.然而,我的RouteTab组件具有响应行为,当移动时它使用 Select 来显示项目菜单。 To simulate Link behavior I am using history.push , the url changes but the page doesn't re-render.为了模拟链接行为,我正在使用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>

Here is a complete example https://codesandbox.io/s/patient-care-router-45t5w这是一个完整的例子https://codesandbox.io/s/patient-care-router-45t5w

You don't need another <Router> in routeTab.您不需要在 routeTab 中使用另一个<Router> Doing so seems to create two different router instances and that's why the history.push didn't work.这样做似乎会创建两个不同的路由器实例,这就是 history.push 不起作用的原因。

Here's a working sample that I forked from the sandbox: https://codesandbox.io/s/patient-care-router-2m3oh这是我从沙盒中提取的一个工作示例: https://codesandbox.io/s/patient-care-router-2m3oh

I disabled the responsiveness to test the dropdown within the same view.我禁用了在同一视图中测试下拉菜单的响应能力。

I got the idea from this example in the docs here: https://reacttraining.com/react-router/web/example/modal-gallery我从这里的文档中的这个例子中得到了这个想法: https://reacttraining.com/react-router/web/example/modal-gallery

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

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