我已经在此处查看了一些类似的帖子,但到目前为止我发现的所有内容都是使用 href 重定向到一个全新的网页。
我的 JavaScript 代码中有一个使用 Material-UI 的按钮 <Link>
<Button component={Link} to="/ratings" className={classes.addImage} onClick={this.submitScore}>
此按钮既重定向网页又调用发起服务器请求的函数。现在这段代码似乎运行良好,重定向和运行它的 onClick
功能。但是我最近发现,在没有 WiFi 的情况下运行我的代码通常会导致我的图片上传请求被忽略。我已经有一段时间无法解决这个问题,我目前的理论是单元格数据较慢,并且在调用上传请求之前页面正在重新路由。
虽然这对我来说不太有意义。看起来代码应该在调用链接后运行,但我看到的是图像上传请求在 WiFi 上工作,但在单元格数据上很少工作。
如有任何想法,我们将不胜感激。
如果有帮助,这里是 onClick 函数:
submitScore = () => {
console.log(this.state)
this.props.dispatch({type: 'SUBMIT_SCORE', payload: {ratings: this.props.scores, user_id : this.props.user.id, name: this.state.beerName, url: this.state.filename, notes: this.state.notes, filename: `${this.props.user.id}_${Date.now()}`}})
// this.props.dispatch({type: 'ADD_PICTURE', payload: {picture: this.state.imgSrc, filename: `${this.props.user.id}_${Date.now()}`}})
axios.get('/picture', {params: {filetype: this.state.imageType, filename: this.state.filename}})
.then(response =>{
var signedUrl = response.data;
console.log(response)
console.log(signedUrl)
var headers= {
'Content-Type': this.state.imageType,
};
console.log(...this.state.imageType)
return axios.put(signedUrl, this.state.newfile, {headers:headers});
})
.then(function (result) {
console.log(result,'success');
})
.catch(function (err) {
console.log(err, 'fail');
});
swal({
title: "Good job!",
text: "You clicked the button!",
icon: "success",
timer: 2000,
});
}
最佳答案
除了在您的按钮中链接到新页面之外,您能否将其设置为在成功时重定向?
.then(function (result) {
console.log(result,'success');
window.location.assign('/ratings'); // <-- Redirect here
})
您需要从按钮中删除链接。
关于javascript - 按钮是否可以使用异步 JavaScript 重定向和执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55347011/