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

React Router导航至当前页面时如何实现滚动至顶部

Fixing Scroll to Top for Same-Page Navigation

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 location object with a fresh, unique key value.
  • By adding location.key to the useEffect dependency 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 no preventDefault() on their click handlers that would block the navigation.
  • For React Router v6.4+, you could also use the useNavigation hook to listen for navigation state changes, but the location.key approach is simpler for most use cases.

内容的提问来源于stack exchange,提问作者loocd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:13:11