仅触发路由器容器组件以匹配子路由

时间:2018-03-29 08:39:57

标签: reactjs react-router

我在我的应用中设置了<Switch>

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/login" component={Login} />
  <Route path="/logout" component={Logout} />
  <EnsureLoggedIn>
    <Route exact path="/user" component={User} />
  </EnsureLoggedIn>
  <Route component={NotFound} />
</Switch>

EnsureLoggedIn组件的工作方式不应该对我的问题太重要,尽管我只想提一下它确实使用withRouter HOC来访问match, <{1}}和location道具用于路由/重定向目的。

我希望发生的是history组件仅触发其中匹配的路由。所以在这种情况下,我只想访问EnsureLoggedIn来触发它。其他任何东西都应转移到/user路线。

我发现相反,只要NotFound//login没有匹配,/logout匹配,就会被挂载并呈现什么都没有到EnsureLoggedIn

如何获得我想要的行为?或者,我是以错误的方式解决这个问题,我应该保护&#34;我以完全不同的方式登录路线?

1 个答案:

答案 0 :(得分:1)

我有一个不同的方法,我将组件包装在Route中。

所以这就是我的路由器的样子,请注意Route的组件道具。

<Router history={history}>
  <div>
    <Route component={Navbar} />
    <Switch>
      <Route path="/control" component={AuthRequired(ControlPage)} />
      <Route path="/login" component={RestrictedAccess(LoginPage)} />
      <Route path="/logout" component={AuthRequired(App)} />
      <Route path="/" component={App} />
    </Switch>
  </div>
</Router>

所以这就是我的HOC RestrictedAccess的样子:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";

import { redirectAuthUser } from "../actions";

/*
  HOC that restricts access to certain routes.

  If user is logged in restricts access to pages he wouldn't
  see if he was a guest, 
  example: Redirect if logged in user tried to visit login.
*/

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

    componentWillMount() {
      if (this.props.token) {
        // this.context.router.push("/login");
        this.props.redirectAuthUser();
      }
    }

    componentWillUpdate(nextProps) {
      if (!nextProps.token) {
        // this.context.router.push("/login");
        this.props.redirectAuthUser(); // this is just an action creator                    
                                       // what it does is commented up
      }
    }

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

  const mapStateToProps = state => ({
    token: state.auth.userToken
  });

  const mapDispatchToProps = {
    redirectAuthUser
  };

  return connect(mapStateToProps, mapDispatchToProps)(Authentication);
}

希望这有帮助!