首页 > 解决方案 > 如何使用 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' 会渲染视频组件。有人可以提供一些信息,说明可能出了什么问题,以及我如何确保只使用一组路线?

标签: reactjsroutesreact-router-dom

解决方案


也许只需要处理私有路由上的身份验证,您可以在此处获取更多信息

几个月前我有同样的问题,我所做的是创建一个包装器来检查用户是否拥有查看该项目的必要权限。

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

推荐阅读