React Router异常:点击路由链接时多组件同时显示问题求助
Hey there! Let's tackle this common React Router issue you're facing—when clicking the /function2 NavLink, both Home and Function2 components render at the same time. This is a classic gotcha, so let's break down why it's happening and how to fix it quickly.
Why This Happens
React Router (versions v5 and below) uses partial path matching by default. That means when your URL is /function2, it still matches the route with path="/" because "/" is the starting segment of "/function2". So both routes end up rendering their components.
If you're using React Router v6, this usually happens if you haven't wrapped your routes in the <Routes> component (which enforces exact matching by default).
Solutions
1. For React Router v5 or Earlier: Add the exact Prop
Simply add the exact attribute to your Home route. This tells React Router only to render the Home component when the URL is exactly "/", not any path that starts with "/".
Here's how to update your code:
<BrowserRouter> <div> <div className="sidenav"> <img src={require("../src/images/logo-light.png")} style={{maxWidth:'20vh',maxHeight:'60vh',marginLeft:'2vh'}} /> <a><NavLink to="/">Home</NavLink></a> <a><NavLink to="/function2">Function2</NavLink></a> </div> <div className="content"> {/* Add the exact prop here */} <Route exact path="/" component={Home} /> <Route path="/function2" component={Function2} /> </div> </div> </BrowserRouter>
2. For React Router v6+: Use <Routes> Component
In v6, the old <Switch> component is replaced with <Routes>, which automatically uses exact matching. You'll also need to use the element prop instead of component to pass your components.
Update your code like this:
import { Routes, Route } from 'react-router-dom'; <BrowserRouter> <div> <div className="sidenav"> <img src={require("../src/images/logo-light.png")} style={{maxWidth:'20vh',maxHeight:'60vh',marginLeft:'2vh'}} /> <a><NavLink to="/">Home</NavLink></a> <a><NavLink to="/function2">Function2</NavLink></a> </div> <div className="content"> <Routes> <Route path="/" element={<Home />} /> <Route path="/function2" element={<Function2 />} /> </Routes> </div> </div> </BrowserRouter>
Quick Check
Double-check that your route components are structured correctly—make sure you're not accidentally rendering both components outside of the route matching logic too. But based on your description, the partial matching issue is almost certainly the culprit here.
Give either of these fixes a try, and your routing should work as expected!
内容的提问来源于stack exchange,提问作者ahmad bilal

