reactjs react v6中的公共和私有路由[重复]

dkqlctbz  于 2023-03-29  发布在  React
关注(0)|答案(2)|浏览(144)

此问题在此处已有答案

How to create a protected route with react-router-dom?(5个答案)
昨天关门了。
我试图在我的项目中实现私有和公共路由。但它不起作用。我遵循最新的方法。我尝试了很多,但无法找出解决方案。登录是在公共路由中。PageLayout及其子项是在私有路由中。将来,我也会添加角色。
Index.js:

const router = createBrowserRouter([
  {
    path: "/signin",
    element: <Signin />,
  },
  {
    path: "/",
    element: <PrivateRoute isAuth={true} element={<PageLayout />} />,
    errorElement: <ErrorPage />,
    children: [
      {
        index: true,
        element: <Dashboard />,
      },
      {
        path: "dashboard",
        element: <Dashboard />,
      },

      {
        path: "doctors",
        element: <DoctorsPage />,
      },
      {
        path: "adddoctor",
        element: <AddDoctorPage />,
      },
])

PrivateRoute.js:

const PrivateRoute = ({ element: Element, isAuth, ...rest }) => {
  const navigate = useNavigate();

  useEffect(() => {
    if (!isAuth) {
      navigate("/signin", { replace: true });
    }
  }, [isAuth, navigate]);

  return isAuth ? <Route {...rest} element={<Element />} /> : null;
};

export default PrivateRoute;
qc6wkl3g

qc6wkl3g1#

我注意到代码中的一个错误:在PrivateRoutes.js中,您需要使用来自react-router-dom<Outlet />,而不是<Route />

return isAuth ? <Outlet /> : <h1>Authenticated</h1>;

修复后应该可以正常工作。我在此处诊断了此问题:https://codesandbox.io/s/naughty-nobel-pphwjx?file=/src/index.js
您可以在这里参考他们的文档:https://reactrouter.com/en/main/start/tutorial

atmip9wb

atmip9wb2#

const router = createBrowserRouter([   {
    path: "/signin",
    element: <PublicRoute isAuth={true} element={<Signin />} />,   },   {
    path: "/",
    element: <PrivateRoute isAuth={true} />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: "/",
        element: checkUserRole(
          ["superadmin", "admin", "hospital"],
          <PageLayout />
        ),
        children: [
          {
            index: true,
            element: <Dashboard />,
          },
          {
            path: "dashboard",
            element: <Dashboard />,
          },

          {
            path: "doctors",
            element: <DoctorsPage />,
          },
          {
            path: "adddoctor",
            element: checkUserRole(["superadmin"], <AddDoctorPage />),
          },
          {
            path: "patients",
            element: checkUserRole(["superadmin"], <PatientsPage />),
          },
          {
            path: "appointments",
            element: checkUserRole(["superadmin"], <AppointmentsPage />),
          },
        ],
      },
    ],   }, ]);
const PrivateRoute = ({ isAuth }) => {   const navigate = useNavigate();

  useEffect(() => {
    if (!isAuth) {
      navigate("/signin");
    }   }, [isAuth]);

  return isAuth ? <Outlet /> : <Navigate to="/signin" />; };

export default PrivateRoute;

相关问题