简体   繁体   中英

issue with how to render with react router

I have this specific case where if the user routes to say topics/rendering, I need to show him a seperate Component and when user routes to topics/10, I need to show him another Component. The problem I am facing right now is that even when I do topics/rendering, I see both of the components being rendered on screen. Also when user routes to topics/math/10, I need to route him to a different page.

Here is the routing part in my App.js (default App.js)

<div className="App">
    <Router>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route exact path="/topics" component={Topics} />
      <Route exact path ="/topics/rendering" component={Description}/>
      <Route  exact path="/topics/:id" component={Topic} />
      <Route path="/topics/:description/:id" component={TopicExtended}/>
    </Router>
  </div>

You want to wrap the Route components in a Switch component so that only one of them will be rendered at a time.

<div className="App">
  <Router>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
      <Route path="/topics/rendering" component={Description} />
      <Route path="/topics/:id" component={Topic} />
      <Route path="/topics/:description/:id" component={TopicExtended} />
    </Switch>
  </Router>
</div>

you should put Route tags inside Switch tag

<Router>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    <Route path="/topics" component={Topics} />
    <Route path ="/topics/rendering" component={Description}/>
    <Route path="/topics/:id" component={Topic} />
    <Route path="/topics/:description/:id" component={TopicExtended}/>
  </Switch>
</Router>

but import it first import {Switch} from 'react-router-dom'

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