React.lazyReact.Suspense 可以做

注意了: lazy 不能单独出现,要配合 Suspense

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React,{lazy} from "react";

import {HashRouter,Route, Switch,Redirect} from 'react-router-dom'
import Login from "../views/Login/Login";
import Error404 from "../views/Error/Error404";
import FirstPage from "../views/FirstPage/firstPage";
import reduxExample from "../views/ReduxExample/reduxExample";
import LifeCycleExample from "../views/LifeCycle/lifeCycleExample";
import ContextExample from "../views/LifeCycle/useContextExample";
import ReducerDemo from "../views/LifeCycle/reducerDemo";
import UseRefExample from "../views/LifeCycle/useRefExample";

const AdminPage = lazy( () => import ("../views/Admin/Admin") );

// import AdminPage from "../views/Admin/Admin";
export default function IndexRouter() {
  const f1 = ()=>{
    alert("请登录")
  }
  function PermissionExample() {
    if(localStorage.getItem('tokenX')) {
      //如果有 token 或者判断 可以的话,就返回 firstPage
      return <FirstPage />
    }
     
    // alert("没有登录")
    return <div>
         {console.log("hello wolrd")}
         {alert("对不起,你没有这个权限")}
         {f1()}
      <div>
        请登录----
      </div>
    </div>

  }
  
  return (
      <div>
        <React.Suspense fallback={<div>Loading...</div>} >
        <HashRouter  >
          <Switch>
             <Route path="/admin" component={AdminPage} />
              <Route path="/login" exact component={Login}/>
              
              
              <Route path="/404" exact component={Error404}/>

              <Route  path="/backend" component={FirstPage}  />
             
              <Route path="/test" exact component={reduxExample} />
              <Route
                path="/" exact
                component={FirstPage}
              />

              
            
          </Switch>
        </HashRouter>
        <HashRouter  >
          <Switch>
            <Route path="/myadmin" exact component={()=> <div>对不起你没有管理员权限</div>}/>
            <Route path="/myadmin2" exact component={()=> PermissionExample()}/>
          </Switch>
        </HashRouter>
        <HashRouter  >
          <Switch>
            <Route path="/admin3" exact component={()=> <div>这个版本3</div>}/>
            <Route path="/admin3/test" exact component={()=> localStorage.getItem("token")? <div>token:{localStorage.getItem('token')}</div>:<div>你没有token admin3</div>}/>
            <Route path="/lifeCycle"  component={LifeCycleExample} />
            <Route path="/ctx" component={ContextExample} />
            <Route path="/reducer" component ={ReducerDemo} />
            <Route path="/ref" component={UseRefExample} />
          </Switch>
        </HashRouter>
        </React.Suspense>
      </div>
  )
}