Javascript 在React项目中使用axios的最佳实践是什么
我正在create react应用程序中使用axios。使用axios的最佳方式是: 方法1: ajax.js app.js 方法2: ajax.js app.js: app2.jsJavascript 在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,是否有办法使其成为整个应用程序的公共服务?这完全取决于您的项目。如果您的项目更依赖于功能组件,那么继续使用第一种方法 如果您对大多数组件使用类,请使用第二种方法 我通常使用第一种方法,它很简单,并且完全避免了这种
在方法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
)