React Router DOM v6状态未更新:如何传递状态给路由函数?
问题分析与解决
核心问题
你遇到的情况是代码中存在语法错误,导致状态isInstalled没有正确更新,同时路由配置函数的语法问题也阻碍了状态传递:
1. App.tsx 中的语法错误
在useEffect的then回调里,setIsInstalled(true))多了一个右括号,导致代码执行报错,setIsInstalled(true)根本没被执行,所以isInstalled始终保持初始值false;另外client变量未定义,checkIfInstalled调用会存在隐患。
2. routes.tsx 中的语法错误
- 路由配置的
children数组内,子路由对象末尾用了分号;,应改为逗号, return语句末尾多了一个逗号,导致函数返回undefined,useRoutes无法获取正确的路由配置
修复后的代码
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"; // 补充client定义 const transport = createGrpcWebTransport({ baseUrl: "/api", // 替换为你的实际服务地址 }); const client = createPromiseClient(Lucle, transport); function App() { const [isInstalled, setIsInstalled] = useState<boolean>(false); const location = useLocation(); // isInstalled变化时,会重新调用routes生成新路由配置 const content = useRoutes(routes(isInstalled)); useEffect(() => { if (location.pathname === "/admin") { checkIfInstalled(client) .then(() => { console.log("true"); setIsInstalled(true); // 修复多余的右括号 }) .catch(() => setIsInstalled(false)); } }, [location.pathname, client]); // 补充client到依赖数组 return ( <StyledEngineProvider injectFirst> <ThemeProvider theme={theme}> <GlobalStyles /> {content} </ThemeProvider> </StyledEngineProvider> ); }
routes.tsx
import { Outlet, Navigate } from "react-router-dom"; // 导入对应组件,替换为实际路径 import Dashboard from "./components/Dashboard"; import AdminIndex from "./components/AdminIndex"; 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;
关键说明
- 修复语法错误后,
checkIfInstalled成功时setIsInstalled(true)会正确执行,isInstalled状态更新 - 状态更新触发App组件重新渲染,
routes(isInstalled)会被重新调用并传入true,此时routes.tsx的控制台会输出true useRoutes会根据新的路由配置重新渲染页面,InstalledRoutes接收到isInstalled=true后,会渲染<Outlet />对应的Dashboard页面
内容的提问来源于stack exchange,提问作者Vana
相关产品推荐
相关产品推荐

