reactjs 状态未使用react router dom v6更新

w41d8nur  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(137)

我使用状态来控制页面的呈现
App.tsx

import { useState, useEffect } from "react";
import { ThemeProvider, StyledEngineProvider } from "@mui/material/styles";
import { useRoutes, useLocation } from "react-router-dom";
import GlobalStyles from "components/GlobalStyles";
import theme from "theme/Index";

// Components
import { checkIfInstalled } from "utils/rpc";

// RPC Connect
import { createGrpcWebTransport } from "@connectrpc/connect-web";
import { createPromiseClient } from "@connectrpc/connect";
import { Lucle } from "gen/lucle_connect";

import routes from "./routes";

function App() {
  const [isInstalled, setIsInstalled] = useState<boolean>(false);

  const location = useLocation();
  const content = useRoutes(routes(isInstalled));

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

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

字符串
routes.tsx

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

const routes = (isInstalled: boolean) => {
  console.log(isInstalled);
  return [
    {
      element: <InstalledRoutes isInstalled={isInstalled} />,
      children: [
        {
          path: "admin",
          element: <Dashboard />,
          children: [
            { index: true, element: <AdminIndex /> },
          ];
        }
      ]
    }
  ],
};

export default routes;


我可以从控制台看到App.tsx的输出。输出是“true”,但是从routes.tsx,我可以看到“false”输出。所以状态不会传播到routes函数。因此我无法呈现正确的页面。如何将状态传递给routes

jexiocij

jexiocij1#

function InstalledRoutes({ isInstalled }: { isInstalled: boolean }) {
  return isInstalled ? <Outlet /> : null;
}

字符串
做的工作!

相关问题