等待 window.location.href?

5 javascript csv api export-to-csv reactjs

所以这可能是一个奇怪的场景,但我有一个端点(GET,返回 CSV),我使用 window.location.href = "URL" 调用它。由于数据负载过重,此调用可能需要一些时间,因此我希望页面上出现一个加载微调器。

(使用 React)在 onClick 函数的开头,我将加载微调器的状态设置为 true,调用 window.location.href,然后将状态设置为 false。

我已尝试了所有可能的方法,但是一旦 api 完成,我就无法正确加载和隐藏微调器。我尝试过将其包装在承诺中并尝试,但仍然没有运气。

有任何想法吗?我正在尝试做这样的事情:

export = () => {

    this.setState({loading:true});

    window.location.href = "url";

    this.setState({loading:false});

}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 1

如果页面将被 csv 替换...

...然后只需修复拼写错误(而不是loactionlocation并删除this.setState({false})(这也是一个拼写错误,但您不想要)。旋转器可能会启动,最终页面将被 CSV 替换。

如果页面要保留在原处...

...那么我这样做的方法是让一个 cookie 告诉我是否已收到响应:

  1. 确保未设置 cookie。
  2. 确保响应发送 cookie。
  3. 在主页中使用计时器循环查找 cookie 值。

因此,就您而言,大致如下:

export = () => {
    this.setState({loading:true});
    this.clearTheCookieValue();
    window.location.href = "url";
    this.cookieWatchTimer = setInterval(() => {
        if (/*the cookie value has now been set*/) {
            clearInterval(this.cookieWatchTimer);
            this.cookieWatchTimer = 0;
            this.setState({loading: fals});
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

...并在 中componentWillUnmount,清除间隔计时器。