简体   繁体   English

如何使用 React & AXIOS 创建全局处理程序?

[英]How to create a global Handler with React & AXIOS?

I'm using ReactJs & AXIOS in this project and i want to make a global error handler without passing by everywhere the request to add catch to it.我在这个项目中使用 ReactJs 和 AXIOS 并且我想制作一个全局错误处理程序,而不是到处传递添加捕获的请求。 I've a service gathering all the requests and I'm creating a new instance of it and use it我有一个收集所有请求的服务,我正在创建它的一个新实例并使用它

import Axios from 'axios';
import { getSiteId } from '../helpers';

export class BaseService {
  baseRoute;
  promise;
  constructor() {
    let siteUrl = (process.env && process.env.REACT_APP_API_URL) || '';
    this.baseRoute = `${siteUrl}/api/v1`;

  }

  async create(item) {
    return await Axios.post(`${this.generateURL()}/`, item, {
      ...this.configuration,
    })
      .catch(error => {
        return this.errors(error);
      });

  }
  async update(item, id) {
    return await Axios.patch(`${this.generateURL(id)}`, item, {
      ...this.configuration,
    });
  }
  async filter(query) {
    return await Axios.get(`${this.generateURL()}`, {
      ...this.configuration,
      params: query,
    });

}

creating a new instance like so像这样创建一个新实例

let service= serviceFactory.getInstance();

Then access any function然后访问任何 function

how to do a global handler adding.catch to every request and render component for example modal from global place, and not to pass to every place i use the functions at如何做一个全局处理程序添加.catch 到每个请求和渲染组件,例如来自全局位置的模态,而不是传递到我使用函数的每个地方

You could use Axios.create() method.您可以使用Axios.create()方法。 An example from the official documentation.来自官方文档的示例。

export const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Now you can export it to use anywhere like this.现在您可以将其导出以在这样的任何地方使用。

import { instance } from './service'

OR with Common JS或使用 Common JS

const { instance } = require('./service')

Have you checked, error boundry in react.你检查过,反应中的错误边界。 That wrapper component can be wrppaed your whole component and catch any uncatched jS error/exections ans show any fallback UI.该包装器组件可以包装您的整个组件并捕获任何未捕获的 jS 错误/执行并显示任何后备 UI。

https://reactjs.org/docs/error-boundaries.html https://reactjs.org/docs/error-boundaries.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM