我正在尝试将一堆 axios 调用移动到一个单独的实用程序文件中,以便我可以共享它们并避免到处重写相同或相似的 axios 调用。
但是,我不知道如何做到这一点,并且仍然利用调用的 then
和 catch
部分,我可以在其中执行独特的操作,例如更新状态和/或变量。
这是我使用的 axios 调用,我在我的应用程序中对此有类似的变体:
axios({
method: "post",
url: `/api/PlanetTime/Battle/${this.props.levelId}/files/upload`,
data: bodyFormData,
config: {
headers: { "Content-Type": "multipart/form-data" }
}
})
.then(response => {
let newFile = response.data[response.data.length - 1];
this.props.onUploadEnd(response.data);
this.setState({
selectedFile: null,
file: null
});
})
.catch(response => {
console.log("upload error!");
});
那么有没有一种方法可以像这样进行 axios 调用,但让它更通用,这样我就可以接受不同的 url、数据等,并且仍然利用 then
部分电话?
最佳答案
您可以返回 axios
调用。返回 axios 调用(内部调用 axios.request 并返回一个 promise )将允许可链接性:
function createRequest(url, data) {
return axios({
// Set up axios instance config
});
}
然后,当您需要它时,导入它:
createRequest('…', { … })
.then(response => { … })
.catch(error => { … });
关于javascript - 如何隔离和提取常见的 axios 调用以防止代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51387391/