Axios:响应后调用函数

时间:2017-09-26 07:50:20

标签: reactjs axios

我正在将Axios与React.js一起使用。 我想在webservice的响应之后调用一个函数。但它不起作用,这是我的代码:

public onValidateRenammeNature = () => { // bouton valider, renomme la nature
  let id
  let newName
  console.log("this.state.myNature.id : " + this.state.myNature.id)
  id = this.state.myNature.id
  newName = this.refs.nature.getValue()

  axios.post('/UpdateNature', {            
    id: id,
    name: newName
  }).then(

  //here I want to call this function after the webservice is executed, but I don't know how can I do that
  this.getAllNaturesFromData()
  )

  this.setState({
    openRenammeNature: false,                
  });
}

感谢您的帮助:)

3 个答案:

答案 0 :(得分:1)

.then()函数接受函数作为参数,你可以

axios.post('/UpdateNature', {            
            id: id,
            name: newName
        }).then(function(response){
            this.getAllNaturesFromData()
        })
//ES6 Arrow function work as well
axios.post('/UpdateNature', {            
            id: id,
            name: newName
        }).then((response) =>{
            this.getAllNaturesFromData()
        })

答案 1 :(得分:0)

您需要向.then函数发送参数。

axios.post('/UpdateNature', {            
    id: id,
    name: newName
  }).then(function(res){
      if(res.statusCode === 200){
          this.getAllNaturesFromData();      // Your function call
      }
  })

答案 2 :(得分:-1)

public onValidateRenammeNature = () => { // bouton valider, renomme la nature
        let id
        let newName
        console.log("this.state.myNature.id : " + this.state.myNature.id)
        id = this.state.myNature.id
        newName = this.refs.nature.getValue()

        console.log("this.props.natureSelected : " + this.props.natureSelected)
        axios.post('/UpdateNature', {            
            id: id,
            name: newName
        }).then((response) => {
            console.log("onValidateRenammeNature then")
//The code is executed, but the list isn't update ..
            this.getAllNaturesFromData()
        })


    }
相关问题