gpt4 book ai didi

javascript - React - 如何检测页面刷新和重定向用户

转载 作者:行者123 更新时间:2023-12-04 17:15:14 25 4
gpt4 key购买 nike

我需要检测页面刷新并在页面刷新后将用户重定向到另一个页面。我正在尝试这个选项,但它似乎不是正确的方法。首先,因为 performance.navigation.type 似乎已被弃用,其次,我在这里使用了多个效果 Hook ,我不确定这是否正确,有没有更优雅的解决方案的想法?

const EligibilityPage = () => {
const [hasRouteChanged, sethasRouteChanged] = useState(false);
const location = useLocation();

useEffect(() => {
sethasRouteChanged(true);
}, [location]);

useEffect(() => {
if (window.performance) {
if (window.performance.navigation.type == "reload" || window.performance.navigation.type == 1) {
if (!hasRouteChanged) window.location.href = "/personal-details-page";
}
}
}, []);

最佳答案

您当前的工作流程没有问题,但 window.performance.navigation.type 已弃用。 window.performance.navigation 属性在 Navigation Timing Level 2 规范中已弃用。请改用 PerformanceNavigationTiming 接口(interface)。

PerformanceNavigationTiming.type

这是一个 experimental technology .

检查 Browser compatibility table在生产中使用它之前要小心。

检查页面是否在 JavaScript 中重新加载或刷新

const pageAccessedByReload = (
(window.performance.navigation && window.performance.navigation.type === 1) ||
window.performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')
);

alert(pageAccessedByReload);

作为解决方法,我只能建议如果您使用的是 redux,则在 redux(或您使用的任何东西)存储中保存一些值以指示重新加载后的状态,并在第一次路由更改时更新它以指示路由已更改不是因为刷新。

关于javascript - React - 如何检测页面刷新和重定向用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68842602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com