React Router页面跳转异常求助:页面未完全跳转且内容叠加
Hey there! Let's sort out this React Router issue where your page content stacks instead of fully replacing when you click a link. I checked out your repo and spotted the root cause right away—here's how to fix it:
The Core Problem
Your current setup isn't using React Router v6's <Routes> component to wrap your route definitions. Without <Routes>, every matching route gets rendered at the same time, which is why new content shows up below old content instead of replacing it.
Step-by-Step Solution
Update Your App.jsx Structure
Opensrc/App.jsxand first make sure you importRoutesalongsideRoutefromreact-router-dom:import { Routes, Route, Link } from 'react-router-dom';Then wrap all your route definitions inside the
<Routes>component. Your App component should look something like this:function App() { return ( <div className="App"> {/* Keep global elements (like your header/navbar) outside Routes so they stay consistent across pages */} <header> <Link to="/">Home</Link> <Link to="/your-other-page">Other Page</Link> </header> {/* Routes ensures only the matching route's component is rendered */} <Routes> <Route path="/" element={<Home />} /> <Route path="/your-other-page" element={<OtherPage />} /> {/* Add any additional routes here */} </Routes> </div> ); }Check Your Navigation Links
Double-check that you're using React Router's<Link>component for all navigation instead of regular<a>tags. Regular<a>tags trigger full page refreshes, and more importantly, they don't play nicely with the router's component replacement logic.Test the Fix
Fire up your app withnpm startand click your navigation links—your content should now fully replace instead of stacking below the old page.
Why This Works
The <Routes> component in React Router v6 acts like a smart switch: it only renders the first route that matches the current URL. Without it, all routes that match (like the root / and any overlapping paths) would render simultaneously, causing the stacking behavior you experienced.
内容的提问来源于stack exchange,提问作者Yash Choksi

