UNPKG

1.93 kBJSXView Raw
1/**
2 * 定义应用路由
3 */
4import React from 'react';
5import { HashRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
6import path from 'path';
7
8import routes from '@/routerConfig';
9
10const 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
31const 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
77export default router;