简体   繁体   中英

How to get params in nested routes on react router dom v4?

This is how I have defined my router.

   <Switch>
     {routes.map((route, index) => (
        <Route
          {...this.props}
          path={`/${route}`}
          key={index}
          component={props => (
            <Layout
              {...props}
            />
          )}
        />
      ))}
      <Route component={() => <p>Not Found</p>} />
    <Switch>

I generate a few routes from the routes array and for any route that does not match it goes to the not found.

Inside the Layout component I have further created further routes like this -

   <div className={"Actionbar"}>          
      <Route
        path={`${props.match.url}/:item`}
        component={() => <EditCategory {...props} />}
      />            
    </div>

When I navigate to a nested route, lets say /edibles/icecream , i should be able to see icecream as a param value for property item , right? I don't see it and i can't seem to figure out how to get the id param value in this nested routing use case. My param object looks empty now.

Found the solution. props needs to be passed along with the route . Like this -

<div className={"Actionbar"}>          
  <Route
    path={`${props.match.url}/:item`}
    render={(props) => <EditCategory {...props} />}
  />            
</div>

Missing this doesn't pass the match values

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