How to set the DefaultRoute to another Route in React Router

前端 未结 11 1208
心在旅途
心在旅途 2020-12-13 02:11

I have the following:

  
    
            


        
相关标签:
11条回答
  • 2020-12-13 02:26
    import { Route, Redirect } from "react-router-dom";
    
    class App extends Component {
      render() {
        return (
          <div>
            <Route path='/'>
              <Redirect to="/something" />
            </Route>
    //rest of code here
    

    this will make it so that when you load up the server on local host it will re direct you to /something

    0 讨论(0)
  • 2020-12-13 02:28
     <Route name="app" path="/" handler={App}>
        <Route name="dashboards" path="dashboards" handler={Dashboard}>
          <Route name="exploreDashboard" path="exploreDashboard" handler={ExploreDashboard} />
          <Route name="searchDashboard" path="searchDashboard" handler={SearchDashboard} />
          <DefaultRoute handler={DashboardExplain} />
        </Route>
        <Redirect from="/*" to="/" />
      </Route>
    
    0 讨论(0)
  • 2020-12-13 02:29

    The problem with using <Redirect from="/" to="searchDashboard" /> is if you have a different URL, say /indexDashboard and the user hits refresh or gets a URL sent to them, the user will be redirected to /searchDashboard anyway.

    If you wan't users to be able to refresh the site or send URLs use this:

    <Route exact path="/" render={() => (
        <Redirect to="/searchDashboard"/>
    )}/>
    

    Use this if searchDashboard is behind login:

    <Route exact path="/" render={() => (
      loggedIn ? (
        <Redirect to="/searchDashboard"/>
      ) : (
        <Redirect to="/login"/>
      )
    )}/>
    
    0 讨论(0)
  • 2020-12-13 02:41

    I was incorrectly trying to create a default path with:

    <IndexRoute component={DefaultComponent} />
    <Route path="/default-path" component={DefaultComponent} />
    

    But this creates two different paths that render the same component. Not only is this pointless, but it can cause glitches in your UI, i.e., when you are styling <Link/> elements based on this.history.isActive().

    The right way to create a default route (that is not the index route) is to use <IndexRedirect/>:

    <IndexRedirect to="/default-path" />
    <Route path="/default-path" component={DefaultComponent} />
    

    This is based on react-router 1.0.0. See https://github.com/rackt/react-router/blob/master/modules/IndexRedirect.js.

    0 讨论(0)
  • 2020-12-13 02:41

    Jonathan's answer didn't seem to work for me. I'm using React v0.14.0 and React Router v1.0.0-rc3. This did:

    <IndexRoute component={Home}/>.

    So in Matthew's Case, I believe he'd want:

    <IndexRoute component={SearchDashboard}/>.

    Source: https://github.com/rackt/react-router/blob/master/docs/guides/advanced/ComponentLifecycle.md

    0 讨论(0)
提交回复
热议问题