React errorElement 中的无限循环

问题描述 投票:0回答:1

我在反应中遇到无限循环/内存泄漏问题。全局错误处理程序是这样启动的:

export const routesConfig: RouteObject[] = [
{
    path: '/',
    element: <App />,
    errorElement: <ErrorPage />,
    children: [
        (all the routes)
    ],
},

];

用户会话会在一段时间后或用户手动注销后超时。如果有另一个选项卡打开或者用户回来,服务器将返回 401。所以我在 errorPage 中检查的第一件事是这个

if (err.statusCode === 401) {
    window.location.href = '/?nocache=' + Date.now();
}

但这会导致无限循环并且浏览器崩溃。浏览器有数百次对没有缓存的起始页的调用,但它们都被取消了。看来这个

window.location.href
没有执行完全。如果我手动执行,它会起作用。

我有一个简单有效的解决方案:

let reloadTriggered = false;
if (err.statusCode === 401) {
    if (!reloadTriggered) {
        reloadTriggered = true;
        window.location.href = '/?nocache=' + Date.now();
    }
    return;
}

但是我在这里所做的似乎并不是 React 的最佳实践。这里有什么建议吗?

reactjs memory-leaks
1个回答
0
投票

不要使用 window.location.href,而是使用 React-router 中的 useNavigate。

const navigate = useNavigate();

if (err.statusCode === 401) {
    navigate('/?nocache=' + Date.now())
}
© www.soinside.com 2019 - 2024. All rights reserved.