最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Router v4 Nested Routes with Switch - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked May 7, 2017 at 9:49 Okinawa TerminalOkinawa Terminal 1551 gold badge2 silver badges8 bronze badges 3
  • What's stopping you from wrapping the <Switch> with the <App> component? – Alex Moldovan Commented May 7, 2017 at 18:57
  • The App component contains the header, navbar and whatever content is in the route. I don't want the header and navbar to be there on the 404 page. – Okinawa Terminal Commented May 8, 2017 at 19:59
  • 1 then I would use a <Route component={App} /> for displaying your App part and inside the App, you can do the routing between home page and user page. that's the v4 way of doing this – Alex Moldovan Commented May 9, 2017 at 7:36
Add a comment  | 

1 Answer 1

Reset to default 19

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>;
  }
}
发布评论

评论列表(0)

  1. 暂无评论