【发布时间】:2021-09-25 23:39:30
【问题描述】:
我已经浏览了所有 StackOverflow 答案,以获取 react 组件之外的历史实例。我目前正在使用 window.location 在反应组件之外进行路由。这导致应用程序刷新。我想在下面的文件中使用历史实例
尝试过的选项:
How to Access History Object Outside of a React Component
导致 withRouter (或) useLocation() 未定义的位置属性
AuthService.ts
logout() {
if (!isEmpty(localStorage.getItem("authToken"))) {
remove("user/logout").then(() => {
if (window.location.pathname !== "/auth/login") {
localStorage.removeItem("authToken");
window.location.pathname("/auth/login");
}
});
}
}
ApiService.ts
const handleError = (err: AxiosError) => {
if (
err.response?.status === 401 &&
window.location.pathname !== "/auth/login"
) {
window.location.pathname = "/auth/login";
}
captureException(err);
return {
message:
(err.response && err.response.data.message) ||
err.toString().split(":")[1] ||
"Something Went Wrong",
};
};
【问题讨论】:
-
如果你想导航到
/auth/loginurl,你为什么不使用window.history.pushState({}, document.title, /auth/login);? -
您可以简单地存储“导航”对象的引用并从服务中使用它。
标签: reactjs react-router react-router-dom