简体   繁体   English

如何隔离和提取常见的axios调用以防止代码重复?

[英]How can I isolate and extract common axios calls to prevent code duplication?

I'm trying to move a bunch of axios calls to a separate utility file so that I can share them and avoid rewriting the same or similar axios calls all over the place. 我试图将一堆axios调用移到一个单独的实用程序文件中,以便可以共享它们,并避免在各处重写相同或相似的axios调用。

However, I can't figure out how to do this and still take advantage of the then and catch part of the call where I do unique things like updating state and/or variables. 但是,我无法弄清楚如何做到这一点,仍然无法利用then优势, catch一部分我做独特的事情(如更新状态和/或变量)的呼叫。

Here is an axios call that I use and I have similar variations on this across my app: 这是我使用的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!");
  });

So is there a way to have an axios call like this, yet have it be more generic, so that I can accept different urls, data, etc and still take advantage of the then part of the call? 因此,有没有办法像这样进行axios调用,但它具有更通用的名称,以便我可以接受不同的url,数据等,并且仍然可以利用then部分调用呢?

You can return the axios call. 您可以返回axios调用。 Returning the axios call (which internally calls axios.request and returns a promise) would allow chainability: 返回axios调用(内部调用axios.request并返回一个Promise)将允许可链接性:

function createRequest(url, data) {
  return axios({
    // Set up axios instance config
  });
}

Then, when you need it, import it: 然后,在需要时将其导入:

createRequest('…', { … })
  .then(response => { … })
  .catch(error => { … });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM