简体   繁体   中英

Default Route With React Router 4

fI currently have the following routes defined in my application:

/
/selectSteps
/steps
/steps/alpha
/steps/beta
/steps/charlie

Which could also be visualised like this:

- (home)
    - selectSteps
    - steps
       - alpha
       - beta
       - charlie

My root component looks like this:

  <Route path="/" exact component={Home} />
    <Route path="/select-steps" render={() => <StepSelectorContainer />} />
    <Route path="/steps" component={StepsContainer} />

My Steps component does this:

steps.map(step => (
  <Route
    path={fullPathForStep(step.uid)}
    key={shortid.generate()}
    render={() => <StepContainer step={step} />}
  />

This all works nicely, but I don't want steps to exist as route in its own right. Only its child routes should be visitable. So I'm looking to lose the /steps route to leave my routes as:

/
/selectSteps
/steps/alpha
/steps/beta
/steps/charlie

How should I configure my routes for this? Ideally, hitting /steps would redirect to the first child route.

Actually, it's pretty straightforward...

Use Redirect component to... well, redirect.

<Redirect from="/steps" exact to="/steps/whatever" />

exact prop guarantees you won't be redirected from sub-route.

Edit: after all, Redirect does support exact (or strict ) props. No need to wrap in Route . Answer updated to reflect that.

Pedr, I think that this will solve your problem.

<Route path="/" exact component={Home} />
<Route path="/select-steps" render={() => <StepSelectorContainer />} />
<Route path="/steps" component={StepsComponent} />

And then in your StepsComponent render method, you can do this.

<Switch>
{steps.map(step => (
    <Route
        path={fullPathForStep(step.uid)}
        key={shortid.generate()}
        render={() => <StepContainer step={step} />}
    />}
<Redirect from="/steps" exact to="/steps/alpha" />
</Switch>

What this will do is render your steps component because it the route begins with /steps. After that is rendered, then it will render one of the nested routes based off the url. If the url is just "/steps", then it will redirect to the initial route listed here, in this case "/steps/alpa" by rendering the redirect. The Switch will make it so that it only renders one of the routes.

Credit to Andreyco for the redirect code.

I hope this helps.

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