[英]preventing default event on axios error in reactjs
如果 axios.post 出錯,我想防止在 react 中打開鏈接。 我使用了event.preventDefault
但它並沒有阻止鏈接在單擊按鈕時打開。 這是代碼
<Link
to={{
pathname: '/',
data: "success",
}}
>
<div>
<Button
onClick={this.onSubmit}
variant="contained"
color="secondary"
>
Post
</Button>
</div>
</Link>
onSubmit=(ev)=>{
let data = {
title: this.state.title,
content: this.state.content,
username: this.state.data.xusername,
date: new Date().toUTCString(),
};
Axios.post("http://localhost:9000/posts", data)
.then((response) => {
console.log(response);
})
.catch((error) => {
ev.preventDefault();
console.log(error);
});
}
在鏈接中嵌套按鈕是您的問題。 這意味着當您單擊按鈕時,它是您阻止默認設置的按鈕事件。
如果你想在 axios 調用完成后重定向到另一個頁面,你可以這樣做:
<Button
onClick={this.onSubmit}
variant="contained"
color="secondary"
>
Post
</Button>
onSubmit=(ev)=>{
let data = {
title: this.state.title,
content: this.state.content,
username: this.state.data.xusername,
date: new Date().toUTCString(),
};
Axios.post("http://localhost:9000/posts", data)
.then((response) => {
console.log(response);
window.location.replace("/yourpage?var1=value"); // Redirect with vanilla js.
this.props.history.push('/yourpage?var1=value&var2=value'); // Redirect with reactjs.
})
.catch((error) => {
console.log(error); // On error, user will experience no change.
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.