简体   繁体   中英

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.

<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.

<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. To simulate Link behavior I am using history.push , the url changes but the page doesn't re-render.

<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

You don't need another <Router> in routeTab. Doing so seems to create two different router instances and that's why the history.push didn't work.

Here's a working sample that I forked from the sandbox: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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