首页 > 解决方案 > Close modal on successful axios post

问题描述

I've tried changing the state when you manage to do a successful post without any further success.

My Post Method

 saveOnClick = () => {
    axios.put('http://localhost:8080/lagbevakning/revision', {
      revisionId: 36,
      subscriptionId: 21549450,
    })
    .then(function (response) {
        alert("You've sucessfully managed to do that")
        /* here i wish to close the modal */

    })
    .catch(function (error) {
      console.log(error)
        alert("something went wrong")
    })
  }

my state

  state = {
    open: false /* if true, modal is open */
    }

close modal method

close = () => this.setState({ open: false })

Any suggestions on how to close the modal on successful axios post would be much appreciated.

标签: javascriptreactjs

解决方案


正如@Quentin 指出的那样,then. 因此,您需要保留对this单独变量(或常量)的引用。

请执行下列操作 :

saveOnClick = () => {
    const self = this;
    axios.put('http://localhost:8080/lagbevakning/revision', {
      revisionId: 36,
      subscriptionId: 21549450,
    })
    .then(function (response) {
        alert("You've sucessfully managed to do that")
        /* here */ self.close();
        /* here i wish to close the modal */

    })
    .catch(function (error) {
      console.log(error)
        alert("something went wrong")
    })
  }

推荐阅读