1 |
|
2 |
|
3 |
|
4 | import React from 'react';
|
5 | import { HashRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
|
6 | import path from 'path';
|
7 |
|
8 | import routes from '@/routerConfig';
|
9 |
|
10 | const RouteItem = (props) => {
|
11 | const { redirect, path: routePath, component, key } = props;
|
12 | if (redirect) {
|
13 | return (
|
14 | <Redirect
|
15 | exact
|
16 | key={key}
|
17 | from={routePath}
|
18 | to={redirect}
|
19 | />
|
20 | );
|
21 | }
|
22 | return (
|
23 | <Route
|
24 | key={key}
|
25 | component={component}
|
26 | path={routePath}
|
27 | />
|
28 | );
|
29 | };
|
30 |
|
31 | const router = () => {
|
32 | return (
|
33 | <Router>
|
34 | <Switch>
|
35 | {routes.map((route, id) => {
|
36 | const { component: RouteComponent, children, ...others } = route;
|
37 | return (
|
38 | <Route
|
39 | key={id}
|
40 | {...others}
|
41 | component={(props) => {
|
42 | return (
|
43 | children ? (
|
44 | <RouteComponent key={id} {...props}>
|
45 | <Switch>
|
46 | {children.map((routeChild, idx) => {
|
47 | const { redirect, path: childPath, component } = routeChild;
|
48 | return RouteItem({
|
49 | key: `${id}-${idx}`,
|
50 | redirect,
|
51 | path: childPath && path.join(route.path, childPath),
|
52 | component,
|
53 | });
|
54 | })}
|
55 | </Switch>
|
56 | </RouteComponent>
|
57 | ) : (
|
58 | <>
|
59 | {
|
60 | RouteItem({
|
61 | key: id,
|
62 | ...props,
|
63 | })
|
64 | }
|
65 | </>
|
66 | )
|
67 | );
|
68 | }}
|
69 | />
|
70 | );
|
71 | })}
|
72 | </Switch>
|
73 | </Router>
|
74 | );
|
75 | };
|
76 |
|
77 | export default router;
|