Nested routes with react router v4 / v5

后端 未结 11 1998
广开言路
广开言路 2020-11-22 12:34

I am currently struggling with nesting routes using react router v4.

The closest example was the route config in the React-Router v4 Documentation.

I want t

11条回答
  •  Happy的楠姐
    2020-11-22 13:34

    React Router v6

    allows to use both nested routes (like in v3) and separate, splitted routes (v4, v5).

    Nested Routes

    Keep all routes in one place for small/medium size apps:

    
      } >
        } /> 
        } /> 
      
    
    

    const App = () => {
      return (
        
          
            // /js is start path of stack snippet
            } >
              } />
              } />
            
          
        
      );
    }
    
    const Home = () => {
      const location = useLocation()
      return (
        

    URL path: {location.pathname}

    user dashboard

    ) } const User = () =>
    User profile
    const Dashboard = () =>
    Dashboard
    ReactDOM.render(, document.getElementById("root"));

    Alternative: Define your routes as plain JavaScript objects via useRoutes.

    Separate Routes

    You can use separates routes to meet requirements of larger apps like code splitting:

    // inside App.jsx:
    
      } />
    
    
    // inside Home.jsx:
    
      } />
      } />
    
    

    const App = () => {
      return (
        
          
            // /js is start path of stack snippet
            } />
          
        
      );
    }
    
    const Home = () => {
      const location = useLocation()
      return (
        

    URL path: {location.pathname}

    } /> } />

    user dashboard

    ) } const User = () =>
    User profile
    const Dashboard = () =>
    Dashboard
    ReactDOM.render(, document.getElementById("root"));

提交回复
热议问题