简体   繁体   English

防止 reactjs 中 axios 错误的默认事件

[英]preventing default event on axios error in reactjs

I want to prevent opening of link in react if axios.post gets error.如果 axios.post 出错,我想防止在 react 中打开链接。 I used event.preventDefault but it isnt stopping the link from opening on button click.我使用了event.preventDefault但它并没有阻止链接在单击按钮时打开。 Here is the code这是代码

<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);
          });
}

Having a button nested within a link is your problem.在链接中嵌套按钮是您的问题。 This means that when you click the button, it's the button event your preventing default on.这意味着当您单击按钮时,它是您阻止默认设置的按钮事件

If you want to redirect to another page upon axios call completion, you could do so with something like this:如果你想在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM