我们有 SPA 并使用 React Router v6 进行导航。 我的页面每个页面都有一组受限制的网址。 当用户手动输入 url 部分时,有什么方便的方法阻止导航吗?例如: http://localhost:0000/patrol 用户在地址栏中更改 http://localhost:0000/otherway 并按 Enter。如果 /otherway 位于当前页面的受限 URL 集中,我可以阻止此导航吗? 我尝试使用 beforeunload 窗口事件,但它工作不稳定。
const useBlockNavigation = (restrictedUrls: string[]) => {
const navigate = useNavigate();
const location = useLocation();
const [previousLocation, setPreviousLocation] = useState(location.pathname);
useEffect(() => {
const checkNavigation = (newPath: string) => {
return restrictedUrls.includes(newPath);
};
const handleNavigation = () => {
const newPath = location.pathname;
if (checkNavigation(newPath)) {
navigate(previousLocation);
} else {
setPreviousLocation(newPath);
}
};
window.addEventListener('popstate', handleNavigation);
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', handleBeforeUnload);
handleNavigation();
return () => {
window.removeEventListener('popstate', handleNavigation);
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [location, navigate, restrictedUrls, previousLocation]);
};
const MyComponent = () => {
const restrictedUrlsForCurrentPage = ['/restricted-page-1', '/restricted-page-2'];
useBlockNavigation(restrictedUrlsForCurrentPage);
return (
<div>
<h1>Current Page</h1>
</div>
);
};
export default MyComponent;
在页面加载时,您可以检查是否输入了特定的(不允许的)网址并重定向到起始页或其他页面:
...
const navigate = useNavigate();
const location = useLocation();
const notAllowedUrls = ['/not', '/allowed', '/urls'];
useEffect(() => {
if (notAllowedUrls.includes(location.pathname)) {
navigate('/');
}
}, [location, navigate]);
...