简体   繁体   中英

preventing default event on axios error in reactjs

I want to prevent opening of link in react if axios.post gets error. I used event.preventDefault but it isnt stopping the link from opening on button click. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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