【问题标题】:React: How to close "loader" after getting file from api completed?React:从 api 获取文件完成后如何关闭“加载器”?
【发布时间】:2019-10-08 13:03:33
【问题描述】:

在下载文件将停止获取后,我遇到了停止“加载器”的问题。在我的情况下,handleDownload() 之后,加载程序仍在屏幕上显示,因为单击按钮后它的状态变为 true。
在 render() 内部

 <div className={`upload-file ${isLoading ? "is-loading-upload" : ""}`}>
      <div className="loader">
           <div className="icon" />
      </div>
  ...
  <button
    className="btn btn-block btn-sm btn-outline-success"
    onClick={() => this.handleDownload(file)}>
     Dowload
  </button>
 </div>

handleDownolad()

  handleDownload = file => {
    Axios.get("/api/files/download", { responseType: "blob", params: { file } })
      .then(res => res.data)
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", file);
        document.body.appendChild(link);
        link.click();
        this.setState({ isLoading: true });
        console.log(file);
      });
  };

一开始isLoading 声明为true,在我得到一些数据后它变得虚假直到触发handleDownload()

【问题讨论】:

  • 当您执行link.click 时,下载将移交给浏览器。您无法知道下载何时完成..
  • 可能,在问问题时我没有写正确。我只需要在它完成Axios.get 之后关闭加载,而不是在它完成下载之后。顺便说一句,感谢您的回复,之前没有提到我在下载时无法处理浏览器事件。

标签: reactjs


【解决方案1】:

请检查一下

handleDownload = file => {
    this.setState({ isLoading: true }); // Set true flag here
    Axios.get("/api/files/download", { responseType: "blob", params: { file } })
      .then(res => res.data)
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", file);
        document.body.appendChild(link);
        link.click();
        this.setState({ isLoading: false }); // Set false flag here
        console.log(file);
      });
  };

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多