【问题标题】:Which is the best practise for using axios in React Project哪个是在 React Project 中使用 axios 的最佳实践
【发布时间】:2020-11-29 19:59:16
【问题描述】:

我在我的 create-react-app 中使用 axios。哪个是使用 axios 的最佳方式:

方法一:

ajax.js

import axios from 'axios';
const axiosInstance = axios.create({});
export default axiosInstance;

app.js

import ajax from './ajax.js';
ajax.post('url');

方法二:

ajax.js

import axios from 'axios';
class AjaxService{
    constructor(apiConfig){
        this.service = axios.create(apiConfig);
    }
    doGet(config){
        return this.service.get(config.url);
    }
    ...
}
export default AjaxService;

app.js:

import AjaxService from './ajax';
const service1 = new AjaxService();
service.doGet({url:'url'});

app2.js

import AjaxService from './ajax';
const service2 = new AjaxService();
service.doGet({url:'url'});

在方法 2 中,我们必须在调用的任何地方初始化服务,这可能是也可能不是最佳实践。如果我们遵循方法 2,有没有办法让它成为跨应用程序的公共服务?

【问题讨论】:

    标签: javascript reactjs rest axios


    【解决方案1】:

    这完全取决于您的项目。如果您的项目更多地依赖函数组件,请继续使用第一种方法。

    如果您对大部分组件使用类,请选择第二种方法。

    我通常使用第一种方法,它很简单并且完全避免了this。此外,定位多个实例也很容易。

    【讨论】:

      【解决方案2】:

      // Ajax.js 文件

      import axios from "axios";
      
      export function updateData=(body,callback){
      le url= 'your api to call'
        axios
          .put(url, body)
          .then((response) => response.data)
          .then((res) => {
            callback(res);
          })
          .catch((error) => {
            console.log(error);
      
            callback('error occurred');
          });
      }
      

      // app.js 文件

      import {updateData} from './ajax.js'
      
      //Place your code where you need
       updateData(yourBodyToPass,res=>{
       //Stuff after the response
       )
      

      注意:-将您的数据作为第一个参数传递并从第二个获取 api 的响应

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 2013-12-11
        • 2021-03-26
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 2022-11-04
        • 2016-05-02
        • 2019-02-19
        相关资源
        最近更新 更多