You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router页面跳转异常求助:页面未完全跳转且内容叠加

Fixing React Router Content Stacking on Navigation

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

  1. Update Your App.jsx Structure
    Open src/App.jsx and first make sure you import Routes alongside Route from react-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>
      );
    }
    
  2. 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.

  3. Test the Fix
    Fire up your app with npm start and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:20:05