react-router-dom动态渲染路由

module.js

import React from 'react';

export function Home() {
    return <h2>Home</h2>;
}

export function About() {
    return <h2>About</h2>;
}

export function Users() {
    return <div><h2>
        Users</h2>
    </div>;
}

export function ErrorPage() {
    return <h1>404Code, GoAway</h1>
}

export function Hello() {
    return <h2>Hello</h2>;
}

export function Say() {
    return <h2>Say</h2>;
}

routes.js

import { Home, About, Users, ErrorPage, Say, Hello, } from './module.js';
const routes = [
    {
        path: '/home',
        component: Home
    },
    {
        path: '/about',
        component: About
    },
    {
        path: '/users',
        component: Users
    },
    {
        path: '/error',
        component: ErrorPage
    },
    {
        path: '/say',
        component: Say
    },
    {
        path: '/hello',
        component: Hello
    },
];

export default routes;

App.js

import React from 'react';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
  useHistory
} from "react-router-dom";
import './App.css';
import routes from './route/index.js';
import { ErrorPage } from './route/module.js';

// 主要代码
function RouteWithSubRoutes(route) {
  console.log(route.path);
  return (
    <Route
      path={route.path}
      render={props => (
        <route.component {...props} routes={route.routes} />
      )}
    />
  );
}

// console.log('app.js', process.env);
function App() {

  return (
    <Router forceRefresh={true}>
      <div>
        <nav>
          <ul>
            {
              routes.map((item) => {
                return <li key={item.path}>
                  <Link to={item.path} >{item.path || '/'}</Link>
                </li>
              })
            }
          </ul>
        </nav>
        <Switch>
          <Route exact path="/" render={() =>
            <Redirect to='/home'></Redirect>} />
          {
            routes.map((route, i) => {
              return <RouteWithSubRoutes key={i} {...route} />
            })
          }
          <Route component={ErrorPage} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

具体细节看官方文档:https://reacttraining.com/react-router/web/example/route-config

注意:

1:动态路径 path 必须 '/pathUrl' 不能为 '/''/非法字符'

2:render={ (props) => {  return <route.component {...props} /> }}

发布了270 篇原创文章 · 获赞 102 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/hahahhahahahha123456/article/details/104700860