在反应中,我尝试使用 onunload 和 onbeforeunload 在重新加载后将用户从当前页面重定向到另一个页面。但第一次重新加载后,它显示网址已更改并再次返回当前页面。第二次重新加载后,它会转到重定向页面。 这些是我尝试过的一些代码...
测试 001:确认/单击“离开页面”按钮后,它应该重定向。事实上,它会转到该页面并重定向到上一页。 >_<
import { useEffect } from 'react';
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
useEffect(() => {
const handleBeforeUnload = (event) => {
// Prevent the default dialog box from showing
event.preventDefault();
// Redirect the user to the desired page
history.push('/redirected-page');
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [history]);
// Rest of your component code...
return (
// JSX for your component...
);
};
测试002:然后我认为可能是计时问题,我设置了一个计时器。现在事情变得更糟了!它不会去那里。
useEffect(() => {
const handleBeforeUnload = (event) => {
event.preventDefault();
// Delay the redirection by 100 milliseconds
setTimeout(() => {
history.push('/Applicant-profile');
}, 100);
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [history]);
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
试试这个:
import React, { useState, useEffect } from 'react'; import { Redirect } from 'react-router-dom'; const MyComponent = () => { const [shouldRedirect, setShouldRedirect] = useState(false); useEffect(() => { const handleBeforeUnload = (event) => { // Custom logic to determine if the page is being reloaded // You can check for specific conditions or simply set the flag to true unconditionally const isReloading = true; if (isReloading) { event.preventDefault(); setShouldRedirect(true); } }; window.addEventListener('beforeunload', handleBeforeUnload); return () => { window.removeEventListener('beforeunload', handleBeforeUnload); }; }, []); if (shouldRedirect) { // Replace 'path/to/redirect' with the actual path you want to redirect to return ;
}
// Render your component content here
return Hello, World! ;
};导出默认的MyComponent;