Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React项目中使用axios的最佳实践是什么_Javascript_Reactjs_Rest_Axios - Fatal编程技术网

Javascript 在React项目中使用axios的最佳实践是什么

Javascript 在React项目中使用axios的最佳实践是什么,javascript,reactjs,rest,axios,Javascript,Reactjs,Rest,Axios,我正在create react应用程序中使用axios。使用axios的最佳方式是: 方法1: ajax.js app.js 方法2: ajax.js app.js: app2.js 在方法2中,无论在哪里进行调用,我们都必须初始化服务,这可能是最佳做法,也可能不是。如果我们遵循方法2,是否有办法使其成为整个应用程序的公共服务?这完全取决于您的项目。如果您的项目更依赖于功能组件,那么继续使用第一种方法 如果您对大多数组件使用类,请使用第二种方法 我通常使用第一种方法,它很简单,并且完全避免了这种

我正在create react应用程序中使用axios。使用axios的最佳方式是:

方法1:

ajax.js

app.js

方法2:

ajax.js

app.js:

app2.js


在方法2中,无论在哪里进行调用,我们都必须初始化服务,这可能是最佳做法,也可能不是。如果我们遵循方法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
 )
注意:-将数据作为第一个参数传递,并从第二个

//Ajax.js文件获取api的响应

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的响应

import AjaxService from './ajax';
const service2 = new AjaxService();
service.doGet({url:'url'});
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');
    });
}
import {updateData} from './ajax.js'

//Place your code where you need
 updateData(yourBodyToPass,res=>{
 //Stuff after the response
 )