2

use Chrome to access ULR : '/home/page1' . (visit '/home' can turn to '/home/page1')

This can't render <Page1>

      <Switch>
        <Redirect from="/home" to="/home/page1" />
        <Route path="/home/page1">
          <Page1 />
        </Route>
      </Switch>

following two methods can render Page1. i want to know WHY!

  • 1 put it behind
      <Switch>
        <Route path="/home/page1">
          <Page1 />
        </Route>
        <Redirect from="/home" to="/home/page1" />
      </Switch>
  • 2 add to ‘exact’ props
      <Switch>
        <Redirect exact from="/home" to="/home/page1" />
        <Route path="/home/page1">
          <Page1 />
        </Route>
      </Switch>
王逍遥
  • 41
  • 4

1 Answers1

3

Within the Switch component path order and specificity matter! You should order the paths from more specific to less specific. This gives the Switch the opportunity to match the more specific paths first, falling back to less specific paths.

Why it doesn't work

"/home" is a path prefix to "/home/page1" and matches both. The following code creates a loop where the path you redirect to also matches the path you are redirecting from. In other words, you are basically redirecting from "/home/page1" to "/home/page1" since "/home/page1" is still matched by "/home".

<Switch>
  <Redirect from="/home" to="/home/page1" />
  <Route path="/home/page1">
    <Page1 />
  </Route>
</Switch>

Version 1

"/home/page1" is more specific than "/home" allowing it to be matched and rendered before the redirect. "/home" doesn't match "/home/page1" and so the first route is skipped. Later the redirect is matched and rendered.

<Switch>
  <Route path="/home/page1">
    <Page1 />
  </Route>
  <Redirect from="/home" to="/home/page1" />
</Switch>

Version 2

Works because the less specific "/home" path must exactly match in order to be matched and rendered. "/home/page1" doesn't exactly match and so the redirect is skipped. Later the route with path="/home/page1" is matched and rendered.

<Switch>
  <Redirect exact from="/home" to="/home/page1" />
  <Route path="/home/page1">
    <Page1 />
  </Route>
</Switch>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181