React中使用Router时出现「元素类型无效」错误的问题排查求助
Let's figure out why you're getting that error and fix it step by step.
First, the error message is pointing to an undefined component being rendered. Looking at your code, here are the key issues:
1. React Router Version Mismatch (Most Likely Culprit)
If you installed the latest version of react-router-dom (v6), the <Switch> component no longer exists—it was replaced with <Routes>. When you try to import Switch from v6, you get undefined, which triggers the "element type invalid" error when React tries to render it.
2. Empty Route Doesn't Render Anything
Your <Route path="/" exact></Route> tag is empty. Even if <Switch> worked, this route wouldn't display the Home component you imported.
3. Missing About Component/Route
You have a link to /about but no corresponding route or About component. This won't cause the current error, but it'll break when users click that link.
Fixes Based on Your React Router Version
If You're Using React Router v6 (Latest)
Update your App.js to use the v6 syntax:
import React from "react"; import Home from "./Home"; // Replace Switch with Routes in imports import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom"; // Optional: Add the About component if you want to use the link function About() { return <h2>You are at About</h2>; } export default function App() { return ( <Router> <div> <Link to="/">Home</Link> <span> | </span> <Link to="/about">About</Link> </div> {/* Use Routes instead of Switch */} <Routes> {/* Use the element prop to pass your component */} <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </Router> ); }
If You're Using React Router v5
Fix the route to render the Home component and add the About route (if needed):
import React from "react"; import Home from "./Home"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; // Optional: Add the About component function About() { return <h2>You are at About</h2>; } export default function App() { return ( <Router> <div> <Link to="/">Home</Link> <span> | </span> <Link to="/about">About</Link> </div> <Switch> {/* Use the component prop to render Home */} <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); }
Quick Checks to Confirm
- Run
npm list react-router-domin your terminal to see which version you're using. If you need to downgrade to v5, runnpm install react-router-dom@5. - Double-check that your
Home.jsis correctly exported (it is, as a default export, and you're importing it properly inApp.js).
内容的提问来源于stack exchange,提问作者Anonymous

