我想将某些页面的权限授予用户,将更多页面的访问权限授予管理员,将所有页面的访问权限授予管理员。
如果用户管理员登录
const role = 'admin'
{role === 'admin' ? (
<>
<Route path='/' component={Home} />
<Route path='/products/' exact={true} component={Products} />
<Route path='/products-edit' exact={true} component={ProductsEdit} />
<Route path='/all-products' exact={true} component={AllProducts} />
</>
)}
如果用户管理员已登录
{role === 'manager' ? (
<>
<Route path='/' component={Home} />
<Route path='/products/' exact={true} component={Products} />
<Route path='/products-edit' exact={true} component={ProductsEdit} />
</>
)}
如果用户登录
{role === 'user' ? (
<>
<Route path='/' component={Home} />
<Route path='/products/' exact={true} component={Products} />
</>
)}
最佳答案
您可以创建一个特殊的 RoleRoute
组件,该组件采用有权访问该路由的 roles
数组,并根据当前的 role
进行检查> 用户拥有的值(value)。如果用户具有适当的角色,那么他们可以访问该路由,否则呈现路由之外的重定向。
示例:
const RoleRoute = ({ role, roles = [], ...props }) => {
return !roles.length || roles.includes(role) ? (
<Route {...props} />
) : (
<Redirect to=".." />
);
};
...
<Switch>
<RoleRoute
path="/products"
role={role}
roles={["admin", "manager", "user"]}
component={Products}
/>
<RoleRoute
path="/products-edit"
role={role}
roles={["admin", "manager"]}
component={ProductsEdit}
/>
<RoleRoute
path="/all-products"
role={role}
roles={["admin"]}
component={AllProducts}
/>
<Route path="/" component={Home} />
<Redirect to="/" />
</Switch>
演示
关于reactjs - 如何在React中进行基于角色的访问路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73578068/