【发布时间】:2021-05-13 02:35:53
【问题描述】:
我有三个不同的用户。我希望他们根据自己的角色访问不同的路线。我在 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
【问题讨论】:
标签: javascript reactjs