所以这可能是一个奇怪的场景,但我有一个端点(GET,返回 CSV),我正在使用 window.location.href = "URL"调用它。由于数据负载繁重,此调用可能需要一些时间,因此我希望在页面上显示加载微调器。
(使用 react ) 在 onClick 函数的开头,我将加载微调器的状态设置为 true,调用 window.location.href,然后将状态设置为 false。
我已尽我所能,但是在 api 完成后我无法正确加载和隐藏微调器。我已经尝试将它包装在一个 promise 中并尝试 .then 但仍然没有运气。
有什么想法吗?我正在尝试做这样的事情:
export = () => {
this.setState({loading:true});
window.location.href = "url";
this.setState({loading:false});
}
最佳答案
如果页面将被 csv 替换...
...然后只需修正拼写错误(您有 loaction
而不是 location
)并删除 this.setState({false})
(这也是一个错字,但你不想要)。微调器可能会启动,最终页面将被 CSV 文件替换。
如果页面要保留在原位...
...那么我这样做的方法是让一个 cookie 告诉我是否已收到响应:
- 确保未设置 cookie。
- 确保响应发送 cookie。
- 在主页中使用计时器循环查找 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});
}
});
}
...并在 componentWillUnmount
中,清除间隔计时器。
关于javascript - 等待 window.location.href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724720/