React路由报错:React.jsx类型无效,ProtectedRoute问题求助
解决React Router ProtectedRoute的"type is invalid"错误
问题场景
在React应用中使用react-router-dom实现ProtectedRoute路由保护组件,尝试保护Dashboard页面时,持续收到类型无效的报错。
报错信息
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <ProtectedRoute />. Did you accidentally export a JSX literal instead of a component? at AppContent at div at div at div at DefaultLayout at RenderedRoute (http://localhost:3000/node_modules/.vite/deps/react-router-dom.js?v=b83527eb:3653:5)
问题根源
路由配置中已经将element设置为已实例化的JSX元素:
{ path: 'dashboard', name: 'Dashboard', element: <ProtectedRoute><Dashboard /></ProtectedRoute> }
但在AppContent.js中渲染路由时,错误地将这个JSX元素当作组件类型再次包裹:
element={<route.element />}
React会尝试将route.element(已经是JSX对象)解析为组件类型,导致类型不匹配报错。
修复步骤
1. 修正AppContent中的路由渲染逻辑
直接使用route.element作为Route组件的element属性值,无需额外包裹:
修改前(错误):
<Route key={idx} path={route.path} exact={route.exact} name={route.name} element={<route.element />} />
修改后(正确):
<Route key={idx} path={route.path} exact={route.exact} name={route.name} element={route.element} />
2. 补充useAuth中的缺失依赖(可选)
检查useAuth.js中的useLocalStorage,该钩子未导入或定义,需要补充实现或导入:
// 示例:自定义useLocalStorage钩子 import { useState, useEffect } from 'react'; function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); const setValue = (value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.error(error); } }; return [storedValue, setValue]; }
将上述代码添加到useAuth.js中,或从第三方库(如react-use)导入。
验证修复
修改完成后重启开发服务,访问Dashboard页面:
- 未登录状态下会自动跳转到/login
- 登录状态下正常显示Dashboard页面
内容的提问来源于stack exchange,提问作者bern_code
相关产品推荐
相关产品推荐

