首页 > 解决方案 > 全局错误处理程序 react/redux saga 并重定向外部组件

问题描述

我正在开发一个使用redux-saga.

我对此有点坚持,所以我正在寻求一些帮助/指导。

我正在尝试实现一个全局错误处理程序,目标是每次 api 发回500用户时都应该重定向到 500 页。

我认为这样做的一个好方法是使用axios interceptors

这是我的拦截器(略读到最低限度):

import axios from 'axios';
import history from '../components/history'; // this is trouble

export default {
  configureAxios: (store) => {
    // Add a response interceptor
    axios.interceptors.response.use((response) => {
      // will work on this later
      return response;
      }, (error) => {
      // catches if the session ended!
      return Promise.reject(error);
    });
    axios.interceptors.response.use(undefined, (error) => {
      // still very much work in progress
      if (error.response.status >= 500) {
        // maybe fire off an action to update the store
        history.push('/500');
      }
      return Promise.reject(error);
    });
   }
 };

这是一个好方法吗?

如果是,我有一个问题,在哪里history.push更新了 url 但没有重定向到页面。我查看了这个答案,但无法正常工作。由于它使用的是react-router-domv4,我虽然遵循这里的建议

npm i history --save 我创建了我的安装历史history.js

import { createBrowserHistory } from 'history';
export default createBrowserHistory();

然后在root.js

import history from './history';
//some stuff here
const App = ({ matchedRoutes }) =>
<div>
  <Head />
  <Header />
  <Switch>
    {matchedRoutes.map((route, i) =>
      <RouteWithSubRoutes key={i} {...route} />
    )}
  </Switch>
  <Main />
</div>;

const Root = ({ store }) => (
  <Provider store={store}>
    <Router history={history}>
      <App matchedRoutes={routes} />
    </Router>
  </Provider>
);

知道我做错了什么吗?关于如何更好地实施这一点的任何建议?

标签: javascriptreactjsredux-saga

解决方案


推荐阅读