【问题标题】:How to replace Link component behavior with History in React-Router如何在 React-Router 中用 History 替换 Link 组件的行为
【发布时间】:2020-09-27 16:33:45
【问题描述】:

在我的应用中

    <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 组件具有响应行为,当 Mobile 使用 Select 来显示项目菜单时。为了模拟 Link 行为,我正在使用 history.push,网址会更改,但页面不会重新呈现。

<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

【问题讨论】:

  • 将其包裹在 withRouter (HOC) 中。使用this.props.history.push(/route) 完成工作。
  • 我已经在使用 useHistory 钩子了。这里不一样吗?
  • 你能说明你在哪里使用useHistory吗?
  • 它在上面的代码框链接中

标签: javascript reactjs react-router browser-history


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 2018-06-05
    • 2021-11-20
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多