React-router-dom v4 nested routes not working

前端 未结 2 1936
悲哀的现实
悲哀的现实 2021-02-05 19:39

In reference to the unresolved question (as a final conclusion)

  • Multiple Nested Routes in react-router-dom v4
  • How to nest routes in React Router v4?
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 20:15

    This is one way of doing what you described (note there are other ways of handling layouts directly in your React Components). In order to keep the example simple, the other components (, etc.) are created as purely functional components with no properties or state but it would be trivial to put each one in its own file as a proper React component. The example below is complete and will run.

    import React, { Component } from 'react';
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    
    class App extends Component {
      render() {
    
        const Header = () => 

    My header

    ; const Footer = () =>

    My footer

    ; const Login = () =>

    Login Component

    ; const Home = () =>

    Home Page

    ; const List = () =>

    List Page

    ; const Settings = () =>

    Settings Page

    ; const PageNotFound = () =>

    Uh oh, not found!

    ; const RouteWithLayout = ({ component, ...rest }) => { return (
    React.createElement(component) } />
    ); }; return (
    ); } } export default App;

    This will do the following, which is hopefully what is now described in your question:

    1. /login has no header or footer.
    2. /, /list, and /settings all have the header and footer.
    3. Any route that is not found will display the PageNotFound component, with no header or footer.

提交回复
热议问题