【问题标题】:Only trigger router container component for matching child routes [duplicate]仅触发匹配子路由的路由器容器组件[重复]
【发布时间】:2018-09-08 03:26:46
【问题描述】:

我的应用中有这个<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 来访问matchlocationhistory用于路由/重定向目的的道具。

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

我发现相反的是,只要//login/logout 不匹配,EnsureLoggedIn 匹配,并被安装和渲染,并且没有任何东西可以到达 NotFound .

如何获得我想要的行为?或者,我是不是走错了路,我应该以完全不同的方式“保护”我登录的路线吗?

【问题讨论】:

  • EnsureLoggedIn 是直接渲染的,因此不会检查其中的路由。检查如何编写经过验证的路由的副本

标签: reactjs react-router


【解决方案1】:

我有一点不同的方法,我将要渲染的组件包装在 Route 中。

所以这就是我的路由器的样子,注意 Route 的 component 属性。

<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);
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2021-08-21
    • 2022-10-12
    相关资源
    最近更新 更多