You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Router v4中实现指定组件树的嵌套路由?

Implementing Nested Routes for Your React Component Tree

Got it, let's get your nested routes up and running smoothly. Here's how to adjust your code step by step:

1. Update App.js to Support Nested Paths

First, remove the exact prop from your Home route. The exact flag would only match /home exactly, which blocks nested paths like /home/contact from rendering the HomeView (and its NavBar).

// App.js
class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          {/* Remove the exact prop to allow nested paths under /home */}
          <Route path="/home" component={HomeView} />
          {/* Add your Login route here later if needed, e.g.: */}
          {/* <Route exact path="/" component={Login} /> */}
        </div>
      </BrowserRouter>
    );
  }
}
render(<App />, document.getElementById('root'));

2. Create the Contact Component

Make a simple Contact component that renders your desired text:

// Contact.js
export const Contact = () => {
  return <div>hello text</div>;
};

3. Add Nested Routes to HomeView

Inside your HomeView, use the match.path prop (automatically passed by React Router) to define relative nested routes. This ensures your paths stay linked to the parent route, making your code easier to maintain. We'll add a route for /home/contact that renders the Contact component.

// HomeView component
import { Contact } from './Contact'; // Don't forget to import the Contact component

export const HomeView = ({ match }) => {
  return (
    <div>
      <NavBar />
      {/* Nested routes go here */}
      <Route path={`${match.path}/contact`} component={Contact} />
      {/* You can add the About route later the same way: */}
      {/* <Route path={`${match.path}/about`} component={About} /> */}
    </div>
  );
};

Your existing NavBar links are already correct—they point to /home and /home/contact, which will now trigger the appropriate routes. When you click "Contact", the NavBar stays visible (since it's part of the parent HomeView) and the Contact component renders below it.

How It All Works

  • Visiting /home will render just the HomeView with the NavBar (you can add default home content here if you want).
  • Clicking "Contact" changes the URL to /home/contact, which matches the nested route in HomeView. The NavBar remains, and the Contact component loads right below it.

That's it! Your nested routing should now behave exactly as you need it to.

内容的提问来源于stack exchange,提问作者Abdul Khader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:34:02