React router v4 - 使用 HOC 的授权路由

React router v4 - Authorized routes with HOC

我在防止未经授权的用户访问仅授权的 routes/components - 例如登录用户仪表板时遇到问题

我有以下代码:

import React from 'react'
//other imports
import {withRouter} from 'react-router'

class User extends React.Component {
  constructor(props) {
    super(props)
    console.log('props', props)
    let user = JSON.parse(localStorage.getItem('userDetails'))
    if(!user || !user.user || props.match.params.steamId !== user.user.steamId) {
      props.history.push('/')
    } else {
      this.props.updateUserState(user)
      this.props.getUser(user.user.steamId)
    }
  }

  //render function
}

//mapStateToProps and mapDispatchToProps

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(User))

路由器:

render() {
    return (
      <Router>
        <div>
          <Route exact path="/" component={Main}/>
          <Route path="/user/:steamId" component={User}/>
          <Route path="/completelogin" component={CompleteLogin}/>
        </div>
      </Router>
    )
  }

我尝试记录以检查是否输入了条件并且它确实是,但是我从渲染函数中收到错误消息,说它无法读取 null 的属性。

有没有办法解决我的问题,还有更好的方法来满足我的要求?只有授权用户才能严格访问特定组件

警告:以下答案使用 React 的旧上下文 API。如果您使用的是 V16.3+,以下答案不适用于您

好的,所以,按照你的逻辑,未经授权的用户是禁止访问用户组件的。简单而公平。没问题。

但我担心的是,您是否正在检查用户是否登录到未经身份验证的用户不应进入的组件内。我认为这是不正确的,因为:

  1. 这是我们程序的额外旅程 - 增加了一些不必要的低效率。有可能我们从路由器转到用户组件,后者将我们送回前者。乒乓.

  2. 用户组件看起来很脏。有无关的逻辑。是的无关紧要。因为不应该在用户组件中进行身份验证检查。用户组件应该包含用户相关的东西。

如果我们不进入用户组件来检查用户身份验证,而是在路由器中进行检查,您会怎么想?用户组件,顾名思义,专供用户使用,检查身份验证的逻辑应该从那里取出。

好的,太棒了。但是如何呢?

我们可以创建一个 Higher-Order Component (HOC) 作为参数,它将接受传递给它的任何组件。然后,我们在 HOC 中添加身份验证逻辑,最后,根据我们使用的逻辑,我们可以重定向到主页或允许对给定组件的请求。

为了让 HOC 能够执行上述操作,它需要访问:

  1. 状态。我们需要知道用户是否登录,状态就是我们存储这些数据的地方。
  2. 路由器。我们可能需要重定向用户。

让我们命名 HOC required_auth。这是它的代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default function(ComposedComponent) {
    class Authentication extends Component {
        static contextTypes = {
            router: React.PropTypes.object
        }

        componentWillMount() {
            if (!this.props.authenticated) {
                this.context.router.history.push('/');
            }
        }

        componentWillUpdate(nextProps) {
            if (!nextProps.authenticated) {
                this.context.router.history.push('/');
            }
        }

        render() {
            return <ComposedComponent {...this.props} />
        }
    }

    function mapStateToProps(state) {
        return { authenticated: state.auth.authed };
    }

    return connect(mapStateToProps)(Authentication);
}

如您所见,这里没有黑魔法。可能令人困惑的是

static contextTypes = {
    router: React.PropTypes.object
}

context is similar to props but it allows us to skip levels in our component hierarchy

因为this.context很容易被访问和滥用,React迫使我们以这种方式定义上下文。

除非您真的知道自己在做什么,否则不要使用上下文。上下文的用例并不常见。阅读更多有关后果的信息 here

总结一下我们的 HOC,它只需要一个组件作为参数,它要么重定向到主页,要么 returns 我们将传递给它的组件。

现在要使用它,在路由文件中我们导入 HOC

 import RequiredAuth from './components/auth/required_auth';

以及任何我们想要保护免受非授权用户访问的路由,我们只需像这样路由它:

<Route path="/user" component={RequiredAuth(User)}/>

上面的行将指向主页或 returns 我们正在传递的组件,User

参考资料: https://facebook.github.io/react/docs/higher-order-components.html https://facebook.github.io/react/docs/context.html

由于您使用的是 React Router 4,因此 Matthew Barbara 的回答虽然绝对正确,但却不必要地复杂。使用 RR4,您可以简单地使用重定向组件来处理您的重定向。有关详细信息,请参阅 https://reacttraining.com/react-router/web/api/Redirect

import React, { Component } from "react";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";

export default function requireAuth (WrappedComponent) {

  class Authentication extends Component {

    render () {

      if (!this.props.authenticated) {
        return <Redirect to="/"/>
      }

      return <WrappedComponent { ...this.props }/>
    }
  }

  function mapStateToProps (state) {
    return { authenticated: state.authenticated }
  }

  return connect(mapStateToProps)(Authentication);
}