How do people handle scroll restoration with react-router v4?

前端 未结 5 410
一整个雨季
一整个雨季 2020-12-28 17:30

I\'m experiencing some problems with scroll positions on the back button (history popstate) when using react-router. React router v4 doesn\'t handle scroll management out of

5条回答
  •  被撕碎了的回忆
    2020-12-28 17:56

    This component scroll to up if page is new but if page seen before restore the scroll.

    scroll-to-top.tsx file:

    import { useEffect, FC } from 'react';
    import { useLocation } from 'react-router-dom';
    
    const pathNameHistory = new Set();
    
    const Index: FC = (): null => {
      const { pathname } = useLocation();
    
      useEffect((): void => {
        if (!pathNameHistory.has(pathname)) {
          window.scrollTo(0, 0);
          pathNameHistory.add(pathname);
        }
      }, [pathname]);
    
      return null;
    };
    
    export default Index;
    
    

    app.tsx file:

    
      
      
    
    

提交回复
热议问题