The use of nested routing in raect (multi-level routing)

1. Introduction

In React, nested routing means that a component contains multiple sub-components, and each sub-component corresponds to a sub-route. This method allows us to organize the page structure more flexibly, and can easily implement page nesting and switching.

In React Router, we can use the component's render attribute or component attribute to render subcomponents, and match routes through the path attribute. Its syntax is as follows:

When using nested routing, we can define some common components in the parent component and then reference them through props.children in the child component. This approach can make the code more concise and easier to understand and debug.

2. Use

When rendering the App component, remember to wrap it with the BrowserRouter tag. If you don’t know why, please see: Basic use of routing in react

 <BrowserRouter>
     <App/>
    </BrowserRouter>
)

Register the parent route in App and jsx.
The MyNavLink here is its own encapsulated NavLink, which is the same as using NavLink.

   <MyNavLink to="/about" >About</MyNavLink>
   <MyNavLink to="/home" >Home</MyNavLink>
   
	<Switch>
        <Route path='/about' component={
    
    About} />
        <Route path='/home' component={
    
    Home} />
	</Switch>

Register sub-routes in the Home component

<MyNavLink to="/home/news">News</MyNavLink>
<MyNavLink to="/home/message">Message</MyNavLink>

 {
    
    /* 
              注册子路由时要带上父路由的 path
              路由匹配是按照注册顺序匹配的
    */}
            <Route path="/home/news" component={
    
    News} />
            <Route path="/home/message" component={
    
    Message} />

Note: When registering a child route, you must bring the path of the parent route, because route matching is based on the registration order.
Personal blog: Yu Sheng’s study notes

Guess you like

Origin blog.csdn.net/m0_63135041/article/details/130321092