![](/img/trans.png)
[英]React: How do I move my ajax api call into a separate component?
[英]how do I make axios API call in a separate component / file?
如何在单独的组件/文件中进行axios API调用?
例:
我创建了包含用于集成axios
的组件的index.jsx文件,此后,我创建了app.jsx
文件以在index.jsx文件中呈现包含axios的index.jsx
文件。
之前感谢
您可以为所有API创建单独的文件夹api
:
假设您拥有AuthenticationAPI
,则必须执行以下操作:
AuthenticationAPI.js
import axios from 'axios';
export const onAuthenticate = payload => {
const URL = `YOUR_URL`;
return axios(URL, {
method: 'POST/GET',
headers: {
'content-type': 'application/json', // whatever you want
},
data: payload,
})
.then(response => response.data)
.catch(error => {
throw error;
});
};
在您的App.js中
import * as AuthenticateAPI from 'api/AuthenticationAPI';
// in your CDM
componentDidMount(){
AuthenticateAPI.onAuthenticate(payload).then((res)=>{ //any payload you want to send just for example
you can get response here in then block
})
}
这是为了基本示例。 您可以使用终极版,如果它变得有必要 ,否则不要滥用它 。
PS: Axios建立在可取消的承诺模式上。 它具有中止控制器。 简而言之,您可以取消任何待处理的网络呼叫,这是使用Observable的绝佳选择。 有时,当您在进行中的API请求之间导航到另一个页面时确实不需要数据时,取消API调用确实很重要,因此数据无用,而AXIOS是唯一的救星。
您可以使用export
functions
即时导入functions
/ methods
创建一个shared.js文件。 例如称它为:apicalls.js
里面这样写你的函数:
apicalls.js
import axios from 'axios';
export function getData(config, callback, errorcallback){
axios.get(url, config)
.then(res => {
//do something
if(callback != null){
callback(res);
}
})
.catch(err => {
// catch error
if(errorcallback != null){
errorcallback(err);
}
})
}
在任何组件中,使用方式如下
// get the location of your apicalls.js file and use to import like below
import { getData } from '../../routetothisjsfile'
//use it
var config = { "Access-Control-Allow-Origin": "*" }
getData(config, (res) => {
//success
},(err) => {
//error
alert(err);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.