简体   繁体   中英

React Router v4 Nested Routes with Switch

Trying to do the following, but it's not working.

ReactDOM.render(
  <Router>
    <div className="route-wrapper">
      <Switch>
        <App>
          <Route exact path="/" component={HomePage} />
          <Route path="/user" component={UserPage} />
        </App>
        <Route component={Err404} />
      </Switch>
    </div>
  </Router>,
  document.getElementById('main')
)

As the documentation says only Route and Redirect elements are allowed inside a Switch element. How do I get this to work without explicitly wrapping HomePage and UserPage in App or having the error page wrapped by App?

While I have begun developing a "Universal React app", where the first page load is done with server-side rendering, I faced similar problem as the React-Router had just updated to 4.0. You should consider restructuring you application something as given below:

ReactDOM.render(
  <Router>
    <div className="route-wrapper">
      <Switch>
        <Route path="/" component={App} />
        <Route component={Err404} />
      </Switch>
    </div>
  </Router>,
  document.getElementById('main')
)

Where the App component is refactored as following:

class App extends React.Component {
  render() {
    return <div>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/user" component={UserPage} />
      </Switch>
    </div>;
  }
}

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