簡體   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