使用 React 状态重定向路由

redirect routes with react state

提问人:Vana 提问时间:9/20/2023 更新时间:9/21/2023 访问量:63

问:

我想检查我的 cms 是否已安装(通过对我的后端进行 api 调用)。 我可以获取该值,我可以在控制台中看到“ok”值,但我没有按预期重定向到 /login。 我怀疑没有更新,isInstalled 状态在更新时不会将其新值发送到路由.js。const content = useRoutes(routes(isInstalled, isLogged));

App.js:

function App() {
  const [isLogged, setIsLogged] = useState<boolean>(false);
  const [isInstalled, setIsInstalled] = useState<boolean>(false);
  const [client, setClient] = useState<any>();
  const content = useRoutes(routes(isInstalled, isLogged));
  const location = useLocation();

  useEffect(() => {
    const transport = createGrpcWebTransport({
      baseUrl: `http://127.0.0.1:50051`,
    });
    const client = createPromiseClient(Lucle, transport);
    setClient(client);

    if (location.pathname == "/admin") {
      check_if_installed(client)
        .then(() => {
         console.log("ok");
         setIsInstalled(true)
         })
        .catch(() => {
          console.log("NOK");
          setIsInstalled(false)
        });
    }
  }, []);

  return (
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <GlobalStyles />
        {content}
      </ThemeProvider>
    </StyledEngineProvider>
  );
}

路由.js

const routes = (isInstalled: boolean, isLogged: boolean) => [
  { path: "/login", element: <Login /> },
  {
    path: "admin",
    element: !isInstalled ? (
      <Navigate to="/install" />
    ) : !isLogged ? (
      <Navigate to="/login" />
    ) : (
      <Dashboard />
    ),
    children: [
      { path: "", element: <AdminIndex /> },
      { path: "editor", element: <OnlineEditor /> },
      { path: "tables", element: <Tables /> },
    ],
  },
  {
    path: "/install",
    element: <Install />,
  },
];

如何更新路线?

reactjs 反应路由器 react-router-dom

评论


答:

1赞 Drew Reese 9/21/2023 #1

导航到 either of 或 仅在路由上发生,并且由于两者最初都开始,因此 UI 将被导航到 either of 或 if starting from 。既不检查状态并导航到其他任何地方。"/login""/install""/admin"isLoggedisInstalledfalse"/login""/install""/admin""/login""/install"

您基本上需要实施路由保护方案。

下面是使用状态和路由进行路由保护的基本示例。

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

const AnonymousRoutes = ({ isLogged }: { isLogged: boolean }) => {
  return isLogged ? <Navigate to="/admin" replace /> : <Outlet />;
};

const PrivateRoutes = ({ isLogged }: { isLogged: boolean }) => {
  return isLogged ? <Outlet /> : <Navigate to="/login" replace />;
};

const InstalledRoutes = ({ isInstalled }: { isInstalled: boolean }) => {
  return isInstalled ? <Outlet /> : <Navigate to="/install" replace />;
};

const UninstalledRoutes = ({ isInstalled }: { isInstalled: boolean }) => {
  return isInstalled ? <Navigate to="/admin" replace /> : <Outlet />;
};
const routes = (isInstalled: boolean, isLogged: boolean) => [
  {
    element: <AnonymousRoutes isLogged={isLogged} />,
    children: [{ path: "/login", element: <Login /> }]
  },
  {
    element: <PrivateRoutes isLogged={isLogged} />,
    children: [
      {
        element: <InstalledRoutes isInstalled={isInstalled} />,
        children: [
          {
            path: "admin",
            element: <Dashboard />,
            children: [
              { index: true, element: <AdminIndex /> },
              { path: "editor", element: <OnlineEditor /> },
              { path: "tables", element: <Tables /> }
            ]
          }
        ]
      },
      {
        element: <UninstalledRoutes isInstalled={isInstalled} />,
        children: [{ path: "/install", element: <Install /> }]
      }
    ]
  }
];

现在,如果当前呈现这些路由中的任何一个并且“应用状态”发生更改,则将重新评估对该路由的访问,并有条件地允许呈现该路由并呈现“受保护”内容呈现重定向到“安全路由”。例如,如果用户未经身份验证并访问“ProtectedRoutes”路由,则重定向到 ,反之亦然,如果他们已通过身份验证并尝试访问 UI,则会将其从该路由反弹回 。Outlet"/login""/login""/admin"

演示

Edit redirect-routes-with-react-state