简体   繁体   English

使用用户角色重用应用程序

[英]React application with users roles

I started working with React/Redux about 2 months ago and I want to make an application with user roles. 我大约2个月前开始使用React / Redux,我想创建一个具有用户角色的应用程序。 When a user logs in I want to change my Route component: 当用户登录时,我想更改我的Route组件:

<Route path={"/"} component={MainPage}></Route>

To component 组件

<Route path={"/"} component={MainPageUser}></Route>

If admin 如果是管理员

<Route path={"/"} component={MainPageAdmin}></Route>

But if I make a switch with my Router I get the error 但是,如果我使用我的路由器进行切换,我会收到错误消息

Warning: [react-router] You cannot change <Router routes>; it will be ignored

I want make access based on the type of account. 我希望根据帐户类型进行访问。

One option is to create a single component for the / path, and within that component return a different component based on the user role. 一种选择是为/ path创建单个组件,并在该组件内根据用户角色返回不同的组件。

<Route path={"/"} component={Home} userRole={userRole}></Route>

class Home extends React.Component {
  render() {
    return this.props.userRole === "admin" ? <HomeAdmin /> : <HomeVisitor />;
  }
}

I recommend you rootPageComponent wrapping the switchs. 我建议你rootPageComponent包装开关。

How about this? 这个怎么样?

(Below is a just simple sample code. Please note that it does not work correctly) (下面是一个简单的示例代码。请注意它无法正常工作)

<Route path={"/"} component={RootPage}></Route>

// RootPage.js
export default const RootPage({role}) => {
    switch(role) {
        case USER: return <MainPageUser />
        case ADMIN: return <AdminPage />
        default: return <MainPage />
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM