React 路由器 - 从外部组件导航时页面不会改变

React router - page doesn't change when navigating from outside component

我正在尝试在收到 403 api 响应后将用户重定向到 "Not Authorized" 页面。这是我到目前为止得到的:

创建了我自己在 React 组件之外使用 history.push 的历史记录

import { BrowserRouter } from "react-router-dom"
import { createBrowserHistory } from "history"

export const history = createBrowserHistory()

export default class OwnBrowserRouter extends BrowserRouter {
  history
}

然后我得到了一个这样的 api 处理程序:

import { history } from "./my-own-history"

const responseErrorHandler = error => {
  const status = _get(error, "response.status")
  if (status === 403) {
    history.push(getRoutePath("not-authorized"))
  }

  throw error
}

const requestFactory = (
  method,
  url,
  body = {},
  useToken = true,
  ownToken = ""
) => {
  ... not important code here ...

  return axios(url, config)
    .then(responseSuccessHandler)
    .catch(responseErrorHandler)
}

最后我有一个 Article 页面,我在其中调用 redux 操作 retrieveArticle(id)。如果用户无权查看文章,则浏览器的路由会正确更改为 /not-authorized,但文章组件会保持呈现状态(页面不会更改)。 当我将 .then(() => this.props.history.push("/not-authorized")) 添加到 redux 操作调用时,它开始工作,但我不想将它添加到我应用程序中的每个 api 调用中......我想为所有人解决全球问题api 调用我的 api 处理程序。

改变

export default class OwnBrowserRouter extends BrowserRouter {
  history
}

export default class OwnBrowserRouter extends BrowserRouter {
  history = history;
}

Class fields proposal 中所述,某些转译器可能会完全忽略该字段。因此将使用原始历史记录(在原始 BrowserRouter 中创建的历史记录)。

Both public and private field declarations create a field in the instance, whether or not there's an initializer present. If there's no initializer, the field is set to undefined. This differs a bit from certain transpiler implementations, which would just entirely ignore a field declaration which has no initializer.