SoFunction
Updated on 2025-04-11

Detailed explanation of the control of routing permissions for React encapsulation advanced components

What is React Advanced Component

Official explanation:

Advanced Components (HOCs) are an advanced technique in React for multiplexing component logic. HOC itself is not part of the React API, it is a design pattern formed based on the combination characteristics of React.

A high-order component (HOC) is a function, and the function takes a component as a parameter and returns a new component. It is just a component's design pattern, which is inevitably generated by the combined properties of react itself. We refer to them as pure components because they can accept any dynamically provided child components, but they do not modify or copy any behavior in their input components.

Pros and cons of HOC

  • Advantages: Logical multiplexing does not affect the internal logic of the wrapped component.
  • Disadvantages: Props passed to the wrapped component are easily duplicated with the wrapped component and then overwritten.

What to do with routing permission control

The main thing is to determine whether the user is logged in. Only by logging in and getting a valid token can you jump to the page.

Ideas:

Determine whether there is a token. If there is a token, it returns a normal component. If there is no token, it jumps to the login page.

accomplish:

Because it is ts, the parameter type is defined first.ReactElementRepresents a React element such as: <div/> or a component. After that, we get the token and jump to the corresponding page through the judgment of the existence or absence of the token.

Code

Encapsulation of advanced components:

interface AuthRouteProps {
  children: ;
}
export function AuthRoute({ children }: AuthRouteProps) {
  const token = getToken();
  if (token) {
    return &lt;&gt;{children}&lt;/&gt;;
  } else {
    // Navigate with Navigate component    ("Please log in first");
    return &lt;Navigate to="/login" /&gt;;
  }
}

In the routing configuration file, introduce encapsulated components, such as:

children: [
      {
        index: true,
        element: &lt;Chat /&gt;
      },
      {
        path: '/paint',
        element: (
          &lt;AuthRoute&gt;&lt;Paint /&gt;&lt;/AuthRoute&gt;
        )
      },
      {
        path: '/me',
        element: &lt;div&gt;mine&lt;/div&gt;
      }
    ]

shortcoming

At present, it is just to determine whether the token exists or not. If the token fails, it will still jump. If the page you jumped to needs to carry a token, it can be processed in the response interceptor: the token will be sent to the backend, and the backend will later determine whether the user exists through decryption.

// Add a response interceptor(
  function (response) {
    // The status codes in the range 2xx will trigger this function.    // Do something about the response data    return ;
  },
  function (error) {
    // Status codes outside the 2xx range will trigger this function.    // Do something to respond to errors    if( === 401){
      removeToken()
      ('/login')
      ()
    }
    return (error);
  }
);

If you just simply jump to the page, you need to modify it and send a request to the backend. The backend returns to the frontend token through processing. Is it valid?

export async function AuthRoute({children}){
  const token = getToken();
  // Send the simulated request to the backend token  const res = await getUserInfo({ token });
  if () {
    return &lt;&gt;{children}&lt;/&gt;;
  } else {
    return &lt;Navigate to="/login" replace /&gt;;
  }
}

Therefore, we need to handle whether user login and token are valid through specific services.

Compare

What is the difference between writing in this way and judging tokens directly on the access page?

Direct judgment when accessing the page: This method is usually performed when the page component is loaded or rendered, that is, the check is performed only after the user has navigated to the page.

useAuthRouteComponent: The judgment is made before the route jump. When a user tries to access a protected route,AuthRouteThe component will first check the token and then decide whether to allow access or redirect.

The above is a detailed explanation of the detailed implementation of the control of routing permissions by React encapsulated high-level components. For more information about React routing permission control, please pay attention to my other related articles!