Javascript 在React中,保护您的路线的最佳选择是什么?

Javascript 在React中,保护您的路线的最佳选择是什么?,javascript,reactjs,authentication,react-router,react-router-dom,Javascript,Reactjs,Authentication,React Router,React Router Dom,我使用这个HOC来保护我的路由,但我发现在每个组件中使用这个HOC都很奇怪,因为我已经使用了1或2个HOC,比如reduxForm等等 import React from "react"; import { connect } from "react-redux"; export default ChildComponent => { class ComposedComponent extends React.Component { componentDidMount()

我使用这个HOC来保护我的路由,但我发现在每个组件中使用这个HOC都很奇怪,因为我已经使用了1或2个HOC,比如reduxForm等等

import React from "react";
import { connect } from "react-redux";

export default ChildComponent => {
  class ComposedComponent extends React.Component {

    componentDidMount() {
      this.shouldNavigateAway();
    }

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



HoC方法是正确的,但您应该将其应用于路由,而不是组件


请看一看

中使用的模式,我不知道您是如何实现路由的,但有一个干净的解决方案

render() {
    let routes = (
      <Switch>
        <Route path="/auth" component={asyncAuth} />
        <Route path="/" exact component={BurgerBuilder} />
        <Redirect to="/" />
      </Switch>
    );

    if (this.props.isAuthenticated) {
      routes = (
        <Switch>
          <Route path="/checkout" component={asyncCheckout} />
          <Route path="/orders" component={asyncOrders} />
          <Route path="/logout" component={Logout} />
          <Route path="/auth" component={asyncAuth} />
          <Route path="/" exact component={BurgerBuilder} />
          <Redirect to="/" />
        </Switch>
      );
    }

    return (
      <div>
        <Layout>
          {routes}
        </Layout>
      </div>
    );
  }

谢谢,这很有魅力,但我有一个问题,为什么有人会使用管理员重定向?你不认为受保护的redriect就足够了吗?redux auth包装中的管理员重定向只是一个在验证后管理ACL的示例,这可能是任何rolethis正在工作,但如果我没有登录,并且我尝试访问一个经过身份验证的组件,我会看到该组件一秒钟,然后再次将其重定向到登录页面,则会出现问题。如何防止这种情况?
const mapStateToProps = state => {
  return {
    isAuthenticated: state.auth.token !== null
  };
};