React路由切换后导航栏激活状态与标题不更新问题求助
问题与解决方案
问题
开发在线测验应用时,使用React Router和Headless UI Disclosure组件,切换到/statistiche等路由时,URL路径正确变化,但导航栏激活状态和头部标题未自动更新,仅刷新页面后才会显示正确状态。
原因
当前代码使用window.location.pathname判断路由,而React Router是单页应用,路由切换属于客户端跳转,不会触发组件重新挂载,window.location.pathname的变化无法让React感知到,因此组件不会重新渲染,导致UI状态未更新。
解决方案
使用React Router提供的useLocation钩子获取当前路由路径,这个钩子会在路由变化时自动更新,触发组件重渲染,从而同步更新导航激活状态和头部标题。
修改步骤:
- 从
react-router-dom导入useLocation钩子; - 在组件内调用
useLocation()获取当前路径对象,提取pathname; - 将所有使用
window.location.pathname的地方替换为获取到的currentPath。
修改后的完整代码:
import { Disclosure } from "@headlessui/react"; import { Routes, Route, Link, useLocation } from "react-router-dom"; // 新增useLocation导入 import { classNames } from "./utility/utilities"; function App() { const navigationBar = [ { nome: "Home", path: "/home" }, { nome: "Corsi", path: "/corsi" }, { nome: "Proponi Domanda", path: "/proponi-domanda" }, { nome: "Statistiche", path: "/statistiche" }, { nome: "Informazioni", path: "/informazioni" }, ]; // 获取当前路由路径 const { pathname: currentPath } = useLocation(); return ( <div className="min-h-full font-inter"> <div className="bg-gray-800 pb-32"> <Disclosure as="nav" className="bg-gray-800"> <div className="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div className="border-b border-gray-700"> <div className="flex items-center justify-between h-16 px-4 sm:px-0"> <div className="flex items-center"> <div className="flex-shrink-0"> <p className="uppercase text-white font-bold">Quiz App</p> </div> <div className="hidden md:block"> <div className="ml-10 flex items-baseline space-x-4"> {navigationBar.map((item) => ( <Link key={item.nome} to={item.path} className={classNames( // 替换为currentPath item.path === currentPath ? "bg-gray-900 text-white" : "text-gray-300 hover:bg-gray-700 hover:text-white", "px-3 py-2 rounded-md text-sm font-medium" )} > {item.nome} </Link> ))} </div> </div> </div> <div className="hidden md:block"> <div className="ml-4 flex items-center md:ml-6"></div> </div> </div> </div> </div> </Disclosure> <header className="py-10"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> {/* 替换为currentPath */} <h1 className="text-3xl font-bold text-white">{navigationBar.find((e) => e.path === currentPath).nome}</h1> </div> </header> </div> <main className="-mt-32"> <div className="max-w-7xl mx-auto pb-12 px-4 sm:px-6 lg:px-8"> <div className="bg-white rounded-lg shadow px-5 py-6 sm:px-6"> <Routes> <Route path="/home" element={<h1>Home</h1>} /> <Route path="/corsi" element={<h1>Corsi</h1>} /> <Route path="/proponi-domanda" element={<h1>Proponi Domanda</h1>} /> <Route path="/statistiche" element={<h1>Statistiche</h1>} /> <Route path="/informazioni" element={<h1>Informazioni</h1>} /> </Routes> </div> </div> </main> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者BOGDAN DONICI
相关产品推荐
相关产品推荐

