react-router具有hoc组件的路由以实现自动化

时间:2019-04-16 08:22:40

标签: javascript reactjs authorization

我正在使用react和react-router v4。我有一个要查询的网络API。

此刻,我正在尝试创建一个授权层,以检查用户是否可以访问路由。 这样做的主要问题是查询将是异步的,并且在呼叫解决之前,路由器将处于挂起状态。 我不确定如何处理这种情况,我在React和React-Router方面还是很新的。

因此,我创建了一个HOC函数,用于包装专用路由并在其中进行检入,并通过ajax调用web-api(如果用户有权访问)。

我不确定这是否是检查授权的正确方法,但我陷入了问题。

反应路由器开关

<Switch>
  {routes.map((route, idx) => {
    if (route.component) {
      if (route.private) {
        return withAutorization(<Route
          key={idx}
          path={route.path}
          exact={route.exact}
          name={route.name}
          render={props => (
            <route.component {...props} />
          )} />)
      } else {
        return (<Route
          key={idx}
          path={route.path}
          exact={route.exact}
          name={route.name}
          render={props => (
            <route.component {...props} />
          )} />)
      }
    } else {
      return (null)
    }
  })}
  <Redirect from="/" to="/404" />
</Switch>

HOC withAutorization组件

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

// controller to handle the dao 
import authController from '../../controllers/authController/authController'
const controller = new authController()

// WrappedComponent will be the Route to be rendered if the user is authorized
const withAutorization = (WrappedComponent) => {
  class HOC extends Component {
    constructor(props) {
      super(props)

      // initial state, with loading
      this.state = {
        authorize: false,
        loading: true
      }
    }

    componentWillMount() {
      // the controller call the webapi and ask for authorization, returning a promise
      // the response will be a bool, true authorize, false unauthorize
      controller.hasAccess('action').then((response => {
        this.setState({
          authorize: response,
          loading: !response
        })
      }))
    }

    // loader
    loading() { return (<div className="animated fadeIn pt-1 text-center"><div className="sk-spinner sk-spinner-pulse"></div></div>) }

    content() {
      return (
        <WrappedComponent />
      )
    }

    render() {
      if (this.state.loading) {
        return <this.loading />
      } else {
        if (this.state.authorize) {
          return <this.content />
        } else {
          return (<Redirect to='/login' />)
        }
      }
    }
  }

  return HOC;
}

export default withAutorization;

在一种工作状态下,我很高兴地发现,由于呼叫未决,因此显示并返回了加载程序。

如果调用为resolvend并且响应为true,则表示内容将与WrappedComponent一起显示并返回。

如果调用为resolvend并且响应为false,则表示将返回。

但是我得到了这个错误: 警告:道具类型失败:提供给children的道具Switch无效,应该是一个ReactNode。enter code here

0 个答案:

没有答案