[英]how do I make axios API call in a separate component / file?
How do I make axios API call in a separate component / file? 如何在单独的组件/文件中进行axios API调用?
example: 例:
I created the index.jsx file that contains the component to integrate axios
and after that I created the app.jsx
file to render the index.jsx file containing axios in the index.jsx
file 我创建了包含用于集成
axios
的组件的index.jsx文件,此后,我创建了app.jsx
文件以在index.jsx文件中呈现包含axios的index.jsx
文件。
thanks before 之前感谢
You can create a separate folder api
for all APIs: 您可以为所有API创建单独的文件夹
api
:
Let's say you have AuthenticationAPI
, you have to something like this: 假设您拥有
AuthenticationAPI
,则必须执行以下操作:
AuthenticationAPI.js 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;
});
};
in you App.js 在您的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
})
}
This is for the sake of basic example. 这是为了基本示例。 You can use redux if it becomes the NECESSITY Otherwise don't abuse it .
您可以使用终极版,如果它变得有必要 ,否则不要滥用它 。
PS: Axios is built on cancellable promise pattern. PS: Axios建立在可取消的承诺模式上。 It has it's abort controller.
它具有中止控制器。 In short you can cancel any pending network call which is an great alternative to use Observable.
简而言之,您可以取消任何待处理的网络呼叫,这是使用Observable的绝佳选择。 Cancel API calls is really important sometimes when you don't really need the data while navigation to another page in between ongoing API request so the data is useless and AXIOS is the lone savior.
有时,当您在进行中的API请求之间导航到另一个页面时确实不需要数据时,取消API调用确实很重要,因此数据无用,而AXIOS是唯一的救星。
You can import functions
/ methods
on the fly using export
您可以使用
export
functions
即时导入functions
/ methods
Create a shared.js file. 创建一个shared.js文件。 for example call it: apicalls.js
例如称它为:apicalls.js
inside write your functions as so: 里面这样写你的函数:
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);
}
})
}
In any component, use as follows 在任何组件中,使用方式如下
// 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.