React-router4.0 路由登录拦截

96
饥人谷_黄洪涛
2019.04.15 14:19* 字数 292

创建路由表

const routers = [
  {path: "/", name: "Index", component: './pages/Index'},
  {path: "/login", name: "Login", component: './pages/Login'},
  {path: "/register", name: "Register", component: './pages/Register'},
  {path: "/my", name: "My", component: './pages/My', auth: true},
  {path: "/create", name: "Create", component: './pages/Create', auth: true},
  {path: "/detail/:blogId", name: "Detail", component: './pages/Detail', auth: true},
  {path: "/edit/:blogId", name: "Edit", component: './pages/Edit', auth: true},
  {path: "/user/:userId", name: "User", component: './pages/User', auth: true},
]

遍历路由表

import React, {Component, Suspense, lazy} from 'react';
import {BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom'
import routers from './router'
import {NotFound} from 'pages'
import {Page} from 'components'

class App extends Component {
  async componentWillMount() {
    await this.props.dispatch(authActions.getAuthInfo());
  }

  render() {
      return (
        <Router>
          <Switch>
            {
              routers.map((item, index) => {
                const DynamicComponent = lazy (() => import(`${item.component}/index`)); 
                return <Route key={index} path={item.path} exact render={props => (
                    <Page {...props}>
                      <Suspense fallback={<div>loading...</div>}>
                      {
                        !item.auth
                            ? (<DynamicComponent {...props} />)
                            : (token
                                ? (<DynamicComponent {...props} />)
                                : (<Redirect to={{ pathname: "/login", state: {from: props.location}
                                }}/>)
                            )
                      }
                      </Suspense>
                    </Page>
                )}>
                </Route>
              })
            }
            <Route component={NotFound}/>
          </Switch>
        </Router>
    );
  }
}
export default App;
  • 关于BrowserRouter Switch Route 等可直接查看官方文档
  • 该教程用到了Suspense, lazy来做页面的懒加载,这是react 的新特性, 所以不需要再引入外部的插件来做懒加载, 会在我的另一篇博客中讲到
  • 在遍历路由表的情况下, 会先将layout 组件 Page 放在最外层, 也就是只要不是404页面, layout布局都会渲染,然后再判断 auth ,这个字段是来判断当匹配到这个路由的时候你是否需要做拦截,然后再判断是否有token
  • token的保存存储以及获取则是另外的解决方案

本文标题:react-router4.0 路由登录拦截
文章作者:黄洪涛
发布时间:2019年04月15日 - 23:04
最后更新:2019年04月15日 - 11:04
原始链接:https://hongtao-huang.github.io/react-router 4.0 路由登录拦截/
许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

随笔
Web note ad 1