React项目路由配置后无法跳转About等组件仅显示导航栏如何解决
React路由跳转异常修复方案
问题原因
你当前使用的是React Router v6版本,路由配置沿用了v5版本的语法,同时路由上下文作用域配置错误,导致对应路径的组件无法正常渲染。
需修改的内容
- 将
<Navbar>组件移动到<Router>组件内部,所有用到路由跳转能力的组件(如包含跳转链接的导航栏)必须处于Router的上下文作用域内,才能正常触发路由更新 - React Router v6废弃了
component属性和exact配置项,改用element属性传入组件实例,且默认开启路径精确匹配,无需额外配置exact - 若Navbar中使用原生a标签实现跳转,需替换为React Router提供的
Link组件,避免页面整体刷新导致路由状态丢失
修正后代码
return ( <div className="Container"> <Router> <Navbar></Navbar> <Routes> <Route path="/" element={<Home />}></Route> <Route path="/about" element={<About />}></Route> <Route path="/price" element={<Pricing />}></Route> <Route path="/testimony" element={<Testimonial />}></Route> </Routes> </Router> </div> );
内容的提问来源于stack exchange,提问作者Good LUCK Mordi
相关产品推荐
相关产品推荐

