如何创建具有受保护路由的 HOC 组件?

How to create HOC component with protected route?

我正在使用 react-router dom v6 并且我有类似

的 ProtectedRoute
export const ProtectedRoute = ({
  children,
}: {
  children: JSX.Element;
}) => {
  let location = useLocation();

  const auth = useAuth();


  if (!auth.isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} />;
  }

  // if (isAuthenticated && !userHasRequiredRole) {
  //   return <AccessDenied />;
  // }

  return children;
};

在我的 AppRouter 中

const AppRouter = () => {
  let elements = useRoutes([
    // These are the same as the props you provide to <Route>
    { path: '/login', element: <LoginPage /> },
    {
      path: '/',
      element: (
        // [1] 
        <ProtectedRoute>
          <BasicLayout />
        </ProtectedRoute>
      ),
      children: [
        {
          path: 'sale',
          element: (
            // [2] 
            <ProtectedRoute>
              <Sale />
            </ProtectedRoute>
          ),
        }
      ]
    }
  ])
  return elements
}
  1. 我可以创建 HOC 组件,这样我就不需要像这样写了(.ie WithProtectedRoute)吗?
  2. 我每次都需要像这样将组件放在 ProtectedRoute 中,因为我在路径中放入:'/'?

虽然您可以 创建一个 withProtectedRoute HOC 并包装您要保护的每个组件导出,但还有更多的“react-router-dommethod. Instead of rendering a childrenprop you could render anOutletcomponent for nestedRoutecomponent and render theProtectedRoute` 现在作为布局组件。

示例:

import { Navigate, Outlet } from 'react-router-dom';

export const ProtectedRoute = () => {
  const location = useLocation();

  const auth = useAuth();

  return auth.isAuthenticated
    ? <Outlet />
    : <Navigate to="/login" state={{ from: location }} replace />;
};

...

const elements = useRoutes([
  // These are the same as the props you provide to <Route>
  { path: '/login', element: <LoginPage /> },
  {
    element: <ProtectedRoute />,
    children: [
      {
        path: '/',
        element: <BasicLayout />,
        children: [
          {
            path: 'sale',
            element: <Sale />,
          }
        ],
      },
    ],
  },
]);

阅读更多关于布局路线的信息here