react-router-dom 6.10.0路由跳转失效:隐私政策页面无法显示
修复React Router路由不显示隐私政策页面的问题
问题根源
- 路由路径配置错误:React Router的
path属性对应URL路径,而非本地文件系统路径,你在App.jsx中使用../src/components/pages/Privacy作为路由路径,完全不符合路由规则。 - Link路径错误:
Footer.jsx中使用相对路径./pages/Privacy,导致生成的URL为localhost:5173/pages/Privacy,但路由未匹配该路径。 - 页面结构逻辑错误:当前
App.jsx直接渲染所有主页面组件(Hero、About等),无论路由如何变化这些组件都会显示;隐私政策页面仅在Routes中定义,但没有设置专门的路由出口区域,无法替换显示内容。
修复步骤
1. 重构App.jsx的路由结构
将主页面内容封装为根路径的路由元素,隐私政策页面设置为规范的URL路径(如/privacy),确保路由内容能正确替换显示:
import { Routes, Route } from "react-router-dom"; import { About, Contact, Experience, Tech, Feedbacks, Hero, Navbar, Works, StarsCanvas, Footer, Privacy } from "./components"; const App = () => { return ( <div className="relative z-0 bg-primary"> {/* Navbar 始终显示,不受路由影响 */} <Navbar /> {/* 路由出口:根据当前URL加载对应内容 */} <Routes> {/* 根路径显示主页面内容 */} <Route path="/" element={ <> <div className="bg-hero-pattern bg-cover bg-no-repeat bg-center"> <Hero /> </div> <About /> <Experience /> <Tech /> <Works /> <Feedbacks /> <div className="relative z-0"> <Contact /> <StarsCanvas /> </div> </> } /> {/* 隐私政策页面路由 */} <Route path="/privacy" element={<Privacy />} /> </Routes> {/* Footer 始终显示,不受路由影响 */} <Footer /> </div> ); }; export default App;
2. 修正Footer.jsx的Link路径
将Link的to属性改为绝对路径/privacy,确保路由匹配正确:
import React from "react"; import { Link } from "react-router-dom"; import { styles } from "../styles"; import { logo } from "../assets"; const Footer = () => { return ( <nav className={`${styles.paddingX} w-full flex items-center py-5 bg-primary`} > <div className="w-full flex justify-between items-center max-w-7xl mx-auto"> <div className="flex items-center gap-2"> <img src={logo} alt="logo" className="w-9 h-9 object-contain" /> <p className="text-white/[0.6] text-[15px] font-bold cursor-pointer flex"> Création Yann Cotard. </p> </div> <Link to="/privacy"> <p className="text-white/[0.6] text-[15px] cursor-pointer flex"> Politique de Confidentialité </p> </Link> </div> </nav> ); }; export default Footer;
3. 修正App.jsx的Privacy导入路径
删除原错误的导入语句,直接从./components导入(components/index.js已导出Privacy):
// 替换原单独导入Privacy的代码 import { // ...其他组件 Privacy } from "./components";
验证修复
重启开发服务器后:
- 点击Footer中的隐私政策链接,URL会变为
localhost:5173/privacy - 页面将正确显示Privacy组件内容,主页面内容自动隐藏
- 返回根路径
/时,主页面内容会重新显示
内容的提问来源于stack exchange,提问作者Yann
相关产品推荐
相关产品推荐

