简体   繁体   中英

Nested routes and Switch - how to pass props.match.params.id?

I have been trying to understand nested routes and switch in the React v4 Router. Consider the main router looks like this (simplified):

<Switch>
  <Route path="/" component={LoginPage} exact={true} />
  <Route path="/dashboard/edit/:id" component={DashboardPage} />
  <Route path="/dashboard" component={DashboardPage} />
</Switch>

The "dashboard" component renders the sub-route:

  render(){
    return (
      <div className="note">
        <Route to='/edit/:id' render={(props) =>
          <div>
            <NoteList {...props} />
            <EditNotePage {...props} />
          </div>
        } />
      </div>
    )
  }

The "EditNotePage" component can access the param by:

const mapStateToProps = (state, props) => ({
  note: state.notes.find((note) => note.id === props.match.params.id
});

Is this the correct approach? It seems a little redundant to specify "/dashboard/edit/:id" twice ( ? ) Once in main router and the again in the dashboard component.

However, if I do not match the route in the main router "Switch" the "props.match.params.id" is not accessible since "props.match" will only point to "/dashboard" .

Have I missed something crucial regarding how the React v4 Router works? :)

Kind regards Kermit

Nope, didn't miss anything. That's how react router v4 works. You define full routes. The trick you can use is that you can grab the current path and prepend it to your "nested path".

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