import { useEffect } from 'react';  
import { useLocation } from 'react-router-dom';  

const useScrollRestoration = () => {  
    const location = useLocation();  

    useEffect(() => {  
        // 当页面完成加载时，检查 sessionStorage 并设置滚动位置  
        const savedScrollY = sessionStorage.getItem(`scrollPosition-${location.key}`);  
        if (savedScrollY) {  
            window.scrollTo(0, parseInt(savedScrollY, 10));  
        }  

        // 保存滚动位置  
        const handleScroll = () => {  
            sessionStorage.setItem(`scrollPosition-${location.key}`, window.scrollY.toString());  
        };  

        window.addEventListener('scroll', handleScroll);  

        // 清理滚动位置（根据你的需要选择是否保留）  
        return () => {  
            window.removeEventListener('scroll', handleScroll);  
            sessionStorage.removeItem(`scrollPosition-${location.key}`);  
        };  
    }, [location]);  
};  

export default useScrollRestoration;