首页 > 解决方案 > 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 

标签: javascriptreactjs

解决方案


这已经解决了。我们没有将角色检查和令牌检查委托给反应路由器,而是依赖于所有仪表板的布局包装器。因为他们控制在他们的孩子中显示的内容,所以他们是存储我们的身份验证逻辑的理想场所。


推荐阅读