如何使用react-router-dom有条件地呈现路由?

时间:2019-07-16 22:02:37

标签: reactjs routes react-router-dom

如何在React中使用专有组件设置条件路由? 我希望上传路径在通过身份验证时排他,这是在ComponentdDidMount中设置的。

  render = () => {
    let routes = (
      <Switch>
        <Route path = "/" exact render = {() => <Home />
        <Route path = "/video" render = {() => <Video />} />
        <Route path = "/upload" exact render = {() => <Upload />} />
        <Redirect to = "/foo"/>
      </Switch>
    )
    if(this.props.isAuthenticated){
      routes = (
        <Switch>
          <Route path = "/" exact render = {() => <Dashboard />} />
          <Route path = "/upload`" render = {() => <Upload />} /> 
          <Route path = "/video" render = {() => <Video />} />
          <Route path = "/foo" render = {() => <h1>Foo</h1>} />
          <Redirect to = "/bar" />
        </Switch>
      )
    }
    return (
      <div className="App">
        <Layout>
            {routes}
        </Layout>
      </div>
    )
  }

正确的是,它使用第一组Route组件来检查路由,如果路由不匹配,我将被重定向到'/ foo',然后呈现h1。如果我尝试访问“上传”,我相信它会被渲染一秒钟,然后我最终会无限次重定向到“ / bar”。 '/ video'会渲染视频组件。有人可以提供一些有关发生问题的信息以及如何确保仅使用一组路由的信息吗?

1 个答案:

答案 0 :(得分:0)

也许只需要在专用路由上处理身份验证,就可以获得更多信息here

几个月前,我有一个相同的问题,我要做的是创建一个包装器,以检查用户是否具有查看该商品的必要权限。

render: () => AuthorizeRoute(
      Amortizations, // Component to load
      'anyvalidRole4ex' // {string} constant
    ),

如果您使用的是redux,可能是这样的:

import React from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';

import NotAllowed from './NotAllowed';

export default function HasPermissionWrapper(
  WrappedComponent,
  requiredRoles,
  FallbackComponent
) {
  class HasPermission extends React.PureComponent {
    static propTypes = {
      userRoles: PropTypes.object.isRequired,
    };

    render() {
      const userRoles = this.props.userRoles.toJS();
      const hasPermission = userRoles
        .map(({roleId}) => requiredRoles.includes(roleId))
        .some((checks) => !!checks);

      if (!hasPermission) {
        if (FallbackComponent) {
          return <FallbackComponent />;
        }
        return <NotAllowed userRoles={userRoles} />;
      }

      return <WrappedComponent {...this.props} />;
    }
  }

  const mapStateToProps = ({auth}) => ({
    userRoles: auth.getIn(['user', 'roles']),
  });

  return connect(mapStateToProps)(HasPermission);
}