React Router路由组件无法正常渲染问题求助
React Router 路由组件无法渲染的解决方案
核心问题是你使用了React Router v6的语法(比如<Routes>组件),但仍沿用v5的component属性指定路由组件,这在v6中已不再支持。
修复步骤
将App.js中路由的component属性替换为element,并传入组件的JSX实例(而非组件引用):
修改后的App.js代码:
import React from "react" import { Route, Routes } from "react-router-dom" import Gyms from "./Gyms/Gyms" import Gym from "./Gym/Gym" const App = () => { return ( <Routes> <Route path="/" element={<Gyms />} /> <Route path="/gyms/:slug" element={<Gym />} /> </Routes> ) } export default App;
原因说明
React Router v6对路由API做了彻底简化,移除了v5中的component、render、children等属性,统一用element属性定义路由要渲染的内容,且必须传递JSX元素(即<Component />),不能直接传递组件本身(Component)。
你的index.js外层<Router>和<Routes>的嵌套配置是正确的,无需修改。完成上述调整后,访问/和/gyms/:slug路由就能正常显示对应组件内容了。
内容的提问来源于stack exchange,提问作者laccc___
相关产品推荐
相关产品推荐

