reactjs - 如何使用 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' 会渲染视频组件。有人可以提供一些信息,说明可能出了什么问题,以及我如何确保只使用一组路线?
解决方案
也许只需要处理私有路由上的身份验证,您可以在此处获取更多信息
几个月前我有同样的问题,我所做的是创建一个包装器来检查用户是否拥有查看该项目的必要权限。
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);
}
推荐阅读
- node.js - 安装赛普拉斯的问题
- javascript - 开玩笑 - 从源文件中导入的函数在同一文件中使用函数的模拟实例
- php - 为什么我的 MYSQL 表在我的新 PC 上不存在?
- javascript - 在Vue中的组件中导入jQuery时顶级等待不可用
- python - 使用装饰器时,视图必须是可调用的或列表/元组
- laravel - Laravel-vue:用 if / v-else 显示不同的图标
- python - 如何使用 Python 解析 SOAP WSDL 方法 XML 响应?
- angular - Formly 中的自定义模型
- alsa - 使用 amixer 设置音频使左右不平衡
- python - conda 安装后默认的 jupyter 环境没有意义