javascript - React Js 和 React Router Dom 多用户类型 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
解决方案
这已经解决了。我们没有将角色检查和令牌检查委托给反应路由器,而是依赖于所有仪表板的布局包装器。因为他们控制在他们的孩子中显示的内容,所以他们是存储我们的身份验证逻辑的理想场所。
推荐阅读
- r - 如何循环一列,如果模式匹配,使用 R 计算其他列中的相关字符?
- javascript - Google Scripts 中的简单计数功能
- python - 如何使用字符串列表作为变量名/对象属性?
- python - Discord.py bot 输出到文件 python
- typescript - 开玩笑测试随机失败
- github - 来自私人 github 存储库的 Pip install wheel
- typescript - 给定一个类型,定义一个函数的联合,参数为该类型的键
- python-3.x - TypeError:必须是实数,而不是无类型加上更多错误
- java - 从二维矩阵中提取 JSON 键
- powershell - 如何在csv的哈希表中为一个键设置多个值