[英]React Js and React Router Dom multiple user types Private Routes
我有三个不同的用户。 我希望他们根据自己的角色访问不同的路线。 我在 localstorage 中设置了一个令牌和 userRole,我想让我的受保护路由检查由 redux 检索的 localstorage 中令牌的可用性。
const TeacherRoute =({ component: Component , auth, ...rest}) => (
<Route
{...rest}
render = {props =>{
if(!props.token){
return <Redirect to="/login" />
}else if(props.token !== null){
if (props.userRole !== 'principal'){
if (props.userRole === 'student'){
return <Redirect to="/studentdashboard" />
}else if(props.userRole ==='teacher'){
return <Redirect to="/teacherdashboard" />
}else{
return <Redirect to="/login" />
}
}
}else {
return < Component {...props} />;
}
}}
/>
);
const mapStateToProps = state => ({
token: state.auth.token,
userRole: state.auth.userRole,
});
export default connect(mapStateToProps, )(TeacherRoute);
挑战在于,起初当我在添加教师和 AdminRoute 之前拥有 StudentRoute 时,该路由可能会重定向并禁止那些不是学生的人访问 Student Route,但是当我添加其他两条路由时,我得到了这个错误。
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.```
May you kindly help me fix this problem. Thanks in advance
这已经解决了。 我们没有将角色检查和令牌检查委托给反应路由器,而是依赖于所有仪表板的布局包装器。 因为他们控制在他们的孩子中显示的内容,所以他们是存储我们的身份验证逻辑的理想场所。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.