Cut the crap and look directly at demand:
Suppose an application has the following three pages:
Landing page ---- home.jsx PageA ---- pagea.jsx PageB ---- pageb.jsx
There are three types of users:
Visitor (not logged in) -- can only access the landing page Ordinary user (logged in) -- can access the landing page and page A Administrator (logged in) -- can access all pages
Specific requirements are as follows:
- Visitors to a page other than the landing page automatically jump to the landing page.
- When a common user accesses page B, a message is displayed indicating that the user has no access permission
Analysis demand can get visitors, members, administrators of the authority layer by layer. The permissions of administrators include those of common users, and those of common users include those of tourists.
So first, log in or not as the first level of permission:
The code for withUserPermission.jsx is as follows
import React from 'react';
import { Redirect } from 'react-router-dom';
import { getUser } from '@/user.js'; // Check whether the user has logged in
export default Wrapper => hocProps= > {
const { component: Component, ... rest } = hocProps;const user = getUser();
return( <Wrapper {... rest} component={ props => { return user ? <Component {... Props} / > : < Redirect to = "/ login" / > / / jump to the login page}} / >); }Copy the code
Then in the second level of permissions, check whether you have administrator permissions: withAdminPermission. JSX code is as follows
import React from 'react';
import { getRole } from '@/user.js'; // Get the user role
export default Wrapper => hocProps= > {
const { component: Component, ... rest } = hocProps;const hasPermission = (getRole() === 'admin');return( <Wrapper {... rest} component={ props => { return hasPermission ? <Component {... Props} /> : <h1> Without permission </h1>}} />); }Copy the code
Using these two higher-order components, encapsulate the Route
The code for privateroutes.js is as follows
import { Route } from 'react-router-dom';
import withUserPermission from './withUserPermission';
import withAdminPermission from './withAdminPermission';
export const UserRoute = withUserPermission(Route);
export const AdminRoute = withUserPermission(withAdminPermission(Route)); // Promote permissions from the outside in
Copy the code
The following uses the two packaged Route components to fulfill the above requirements:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { UserRoute, AdminRoute } from './PrivateRoutes';
import PageLogin from 'views/PageLogin';
import PageA from 'views/PageA';
import PageB from 'views/PageB';
export default() => ( <Router> <Route path='/login' component={PageLogin} /> <UserRoute path='/pageA' component={PageA} /> <AdminRoute path='/pageB' component={PageB} /> </Router> );Copy the code