简体   繁体   中英

how to get route param values of child component from parent component in app using React Router

if I have nested routes, /:foo/:bar, how would I get access to match.params.bar from the component rendering /:foo? Is context the most common way to do this or...? Thanks.

Don't mind this paragraph. It's just some filler to fulfill the arbitrarily set quota fjewoifjoai;fiwajfoijaweoifjiowfjoiawjfioawjfwafaweffa

I have an example here as well:

const Header = withRouter(({ match }) => {
  console.log("match>>>", match.params); // what's the most common way for this to have
  // the 'childest' param value?
  return (
    <header>
      <nav id="nav" role="navigation">
        <ul>
          <li>
            <NavLink to="/">Home</NavLink>
          </li>
          <li>
            <NavLink to="/first">First</NavLink>
          </li>
          <li>
            <NavLink to="/second">Second</NavLink>
          </li>
          <ul>
            <li>
              <NavLink to="/second/1">Second -> 1</NavLink>
            </li>
            <li>
              <NavLink to="/second/2">Second -> 2</NavLink>
            </li>
          </ul>
        </ul>
      </nav>
    </header>
  );
});

const HomePage = () => {
  return <h1>HomePage</h1>;
};
const NumPage = props => {
  const num = props.match.params.no;
  console.log("num>>", props.match.params, props.match.path);
  if (num === "second") {
    return (
      <div>
        <h1>{num}</h1>
        <Switch>
          <Route path={`${props.match.path}/:sub`} component={SubPage} />
        </Switch>
      </div>
    );
  }
  return <h1>{num}</h1>;
};
const SubPage = props => {
  return (
    <h1>
      {props.match.params.no} --> {props.match.params.sub}
    </h1>
  );
};

const App = () => (
  <BrowserRouter>
    <div>
      <Header />
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route path="/:no" component={NumPage} />
      </Switch>
    </div>
  </BrowserRouter>
);

You can extend your first Route to check for both the foo as well as the bar parameter like this:

<Route path="/:foo/:bar?" component={NumPage} />

Now your match.params object contains a foo and bar field with the respective values.

You can access these within your child components easily and you dont have duplicated logic with nested routes. By adding the ?, bar becomes optional so that the route "/:foo" is still valid.

Hope this helps. Happy coding.

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