如何在React应用中控制受保护页面的路由?

时间:2018-10-07 14:13:24

标签: reactjs react-redux react-router

我是否需要在每个受保护页面容器中检查auth,以及是否将其错误地重定向到登录页面?如果我有很多受保护的页面怎么办?

2 个答案:

答案 0 :(得分:1)

您可以将高阶组件(HOC)用于路由器。使用专用路由器。

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    fakeAuth.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to='/login' />
  )} />
) 

使用它代替路线。

<PrivateRoute component={component} {...props} />

答案 1 :(得分:1)

正如@Nisfan所说,进行HOC并不是一个坏主意。

例如:

// This HOC redirects to the landing page if user isn't logged in.
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { LANDING } from '../constants/routes';

const ERROR_MESSAGE = 'You need to be logged in to access that page.';

const withAuthentication = (condition, route = LANDING) => (Component) => {
  class WithAuthentication extends React.Component {
    componentDidMount() {
      if (!condition(this.props.userState.loggedIn)) {
        this.props.history.push(route);
        // TODO: show error if you want
      }
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.userState.loggedIn !== this.props.userState.loggedIn) {
        if (!condition(nextProps.userState.loggedIn)) {
          this.props.history.push(route);
          // TODO: show error if you want
        }
      }
    }

    render() {
      return this.props.userState.loggedIn ? <Component /> : null;
    }
  }

  WithAuthentication.propTypes = {
    history: PropTypes.object.isRequired,
    userState: PropTypes.object,
  };

  const mapStateToProps = state => ({
    userState: state.userState,
  });

  const temp = connect(mapStateToProps)(WithAuthentication);

  return withRouter(temp);
};

export default withAuthentication;

然后,当您要保护路由时,可以将条件包装在withAuthentication中。

例如,您的条件可能是该用户是否已登录,或者该用户是否已登录并且是管理员等。