首页 > 解决方案 > 反应路由器私有路由/重定向不适用于 redux

问题描述

我正在尝试设置受保护的路由,如果用户没有登录,他们将被重定向到 /login 页面,但在使用 redux 时它不起作用。

这是我的 ProtectedRoute 组件:

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Route, Redirect } from 'react-router-dom';

import { authenticate } from './actions';

const ProtectedRoute = ({
  component: Component, authenticate, isAuthenticated, ...rest
}) => {
  useEffect(() => {
    authenticate();
  });

  return (
    <Route
      {...rest}
      render={props => (isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect to="/login" />
      ))
      }
    />
  );
};

ProtectedRoute.propTypes = {
  component: PropTypes.elementType.isRequired,
  authenticate: PropTypes.func.isRequired,
  isAuthenticated: PropTypes.bool.isRequired,
};

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

const mapDispatchToProps = {
  authenticate,
};

export default connect(mapStateToProps, mapDispatchToProps)(ProtectedRoute);

这是路线:

<Provider store={store}>
  <Router>
    <Switch>
      <ProtectedRoute exact path="/" component={App} />
      <Route path="/login" component={LoginPage} />
    </Switch>
  </Router>
</Provider>

现在,在您将其标记为重复之前,我已经尝试了其他线程中的解决方案。

使用withRouter不起作用。

withRouter(connect(mapStateToProps, mapDispatchToProps)(ProtectedRoute))

同样的事情{pure: false}

connect(mapStateToProps, mapDispatchToProps, null, {pure: false})(ProtectedRoute);

我也用Switch. 我不知道如何让它工作。

标签: reactjsreduxreact-reduxreact-routerreact-router-v4

解决方案


为什么不使用 HOC 组件来检查身份验证?

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

export default ChildComponent => {
  class ComposedComponent extends Component {

    componentDidMount() {
      this.shouldNavigateAway();
    }

    componentDidUpdate() {
      this.shouldNavigateAway();
    }
    shouldNavigateAway() {
      if (!this.props.auth) {
        this.props.history.push('/');
      }
    }
    render() {
      return <ChildComponent {...this.props} />;
    }
  }
  function mapStateToProps(state) {
    return { auth: state.auth.authenticated };
  }
  return connect(mapStateToProps)(ComposedComponent);
};

现在你只需要将这个组件导入到受保护的组件中,然后像下面这样导出受保护的组件,

import authCheck from 'blah/blah...'

export default authCheck(ProtectedComponent)

推荐阅读