I need to scroll to the top every time the URL changes in my project (and on page reload).
一切都在发挥作用,但我与浏览器背纽州有问题。 即使路径名称改变该网页的斜向上,它也处理所有其他案件(网页重载和定期连接导航)。
我试图通过制造一种习俗来对付这种情况,它只是 back子,但它并没有破坏我所想要的东西。 我也尝试了许多其他事情,但似乎在浏览器后纽顿工作。
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
const ScrollToTop = () => {
const { pathname } = useLocation();
const useBackButton = () => {
const [isBack, setIsBack] = useState(false);
const handleEvent = () => {
setIsBack(true);
};
useEffect(() => {
window.addEventListener("popstate", handleEvent);
return () => window.removeEventListener("popstate", handleEvent);
});
return isBack;
};
const backButton = useBackButton();
console.log(backButton);
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname, backButton]);
useEffect(() => {
window.onbeforeunload = () => {
window.scrollTo(0, 0);
};
}, []);
return null;
};
export default ScrollToTop;