【问题标题】:Access History object outside React component在 React 组件之外访问 History 对象
【发布时间】: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/login url,你为什么不使用window.history.pushState({}, document.title, /auth/login);
  • 您可以简单地存储“导航”对象的引用并从服务中使用它。

标签: reactjs react-router react-router-dom


【解决方案1】:

使用connected-react-router

你需要用redux连接它。

// reducers.js
import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'

const createRootReducer = (history) => combineReducers({
  router: connectRouter(history),
  ... // rest of your reducers
})
export default createRootReducer

【讨论】:

  • 这只有在你使用 Redux 时才有用。在我看来,集成 Redux 来解决这个问题有点过头了。
  • 谢谢,它很酷。但是路由器状态一直显示未定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2017-09-19
  • 1970-01-01
相关资源
最近更新 更多