React Router导航至当前页面时如何实现滚动至顶部
The problem with your current ScrollToTop component is that it only triggers when the pathname changes. When you navigate to the exact same page (like reloading /about after scrolling down), the pathname stays the same—so the useEffect never runs, and the page doesn’t scroll back to top.
Here’s a simple, effective fix:
Modified ScrollToTop Component
Instead of relying on pathname, use the location.key property as your dependency. React Router generates a unique key for every navigation action—even when you navigate to the same route. This ensures the scroll-to-top logic runs every time you navigate, no matter where you’re going.
import { useEffect } from "react"; import { useLocation } from "react-router-dom"; export default function ScrollToTop() { const location = useLocation(); useEffect(() => { window.scrollTo(0, 0); }, [location.key]); // Trigger on every navigation via unique location key return null; }
Why This Works
- Every time you navigate (even to the same page), React Router creates a new
locationobject with a fresh, uniquekeyvalue. - By adding
location.keyto theuseEffectdependency array, we tell React to run the scroll logic whenever this key changes—meaning on every single navigation event.
Quick Checks
- If you’re using
<Link>components to navigate to the same page, ensure there’s nopreventDefault()on their click handlers that would block the navigation. - For React Router v6.4+, you could also use the
useNavigationhook to listen for navigation state changes, but thelocation.keyapproach is simpler for most use cases.
内容的提问来源于stack exchange,提问作者loocd
相关产品推荐
相关产品推荐

