简体   繁体   中英

Returned React-Router <Route> doesn't work in switch

I wrote my application in a very modular way in the way that each package (section of the application) is a package and the only thing i'm returning from each package is a <Route to="/dest" component="something" /> .

The problem that i'm having right now is that, this method of returning are not really working in and that's how i tested it:

The initial setup was something like this :

<Switch>
 <Dashboard {...rest} />
 <Users {...rest} />
 <Quiz {...rest} />
</Switch>

And the Dashboard component is something like this :

...
return (
    <Route exact path="/" render={ props => (
      <Dashboard {...props} {...stuff} />
    )}/>
  )

and almost the same thing for User and Quiz components, which are directly being imported from their module packages.

when i run the application, i can access Dashboard & Users but Quiz is not being rendered. if i change the order and put quiz on top of <Users /> it will work. which means it only can render one after first exact route.

but instead, if i take all those code and write the Routes in the switch itself without referencing to another component, it works like a charm.

<Switch>
 <Route exact path="/" render={ props => (
  <div>demo</div>
 )}/>
 <Route path="/dashboard" render={ props => (
  <div>demo</div>
 )}/>
 <Route path="/users" render={ props => (
  <Users />
 )}/>
 <Route path="/quiz" component="Users"/>              
</Switch>

I've tried both component, and render in route, this one is just a sample

any suggestion on why is this happening ?

UPDATE 1

I haven't managed to figure out what the problem is and what's causing it, but i found a way around it by creating a component that returns a Switch and direct Routes as children. then i exported the Switch to my main app.

<Switch>
  <Dashboard {...rest} />
  <Users {...rest} />
  <Quiz {...rest} />
</Switch>

This will not work because Switch expects Route s to be direct children. It cannot perform its logic on arbitrary wrapper components.

I not sure if that would work but you would have to directly export Route from the module:

Dashboard.js

export default (
  <Route exact path="/" render={ props => (
    <Dashboard {...props} /> 
  )}/>
)

but when you do something like this:

export default (stuff) => (
  <Route exact path="/" render={ props => (
     <Dashboard {...props} {...stuff} />
  )}/>
)

Notice that you are not exporting a Route but a functional component that renders Route.

I personally think that you should only export purely components to be rendered without Route s and leave that up to library consumer.

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