我正在开发一个React应用,并实现了一种单击按钮即可下载文件的方法,点击后调用以下函数即可下载文件。它工作正常,但也可以刷新页面。下载文件后如何停止页面刷新?
printClientsData(popupResponse) {
this._confirmPopup.closePopup();
if (popupResponse) {
this.setState({
loading: true,
showLoadingMsg: true,
loadingText: 'Generating PDF...',
})
var req = new XMLHttpRequest();
req.open("POST", "http://example.com", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("x-auth-token", localStorage.getItem('token'));
req.responseType = "blob";
req.onreadystatechange = (e) => {
if (req.readyState === 4 && req.status === 200) {
let filename = "PdfName-" + new Date().getTime() + ".pdf";
let myHeader = req.getResponseHeader('file-name');
if (myHeader !== null) {
filename = myHeader;
}
if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, filename);
this.setState({
loading: false,
showLoadingMsg: false
})
NotificationManager.success('QR Code Generated Successfully');
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
this.setState({
loading: false,
showLoadingMsg: false
})
NotificationManager.success('QR Code Generated Successfully');
return false
}
e.preventDefault()
}
};
req.send(JSON.stringify(this.selectedClients));
}
}
答案 0 :(得分:0)
这也发生在我身上。我是如此愚蠢,以至于在我的render方法中,我的按钮位于form元素内,因此每次单击该按钮都会刷新页面。因此,请确保在按钮中添加type =“ button”属性或在表单的“ onSubmit”属性中添加preventdefault