2017-09-26 34 views
1

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

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

谢谢您的帮助:)

回答

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() 
     }) 
+0

你是对的,但它不为我工作...我已经编辑我的代码在对方的回答 –

0

你需要发送一个参数给.then函数。

axios.post('/UpdateNature', {    
    id: id, 
    name: newName 
    }).then(function(res){ 
     if(res.statusCode === 200){ 
      this.getAllNaturesFromData();  // Your function call 
     } 
    }) 
-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() 
     }) 


    } 
+0

什么是你所得到的回应,什么,并没有被执行? –

+0

@JamesMaa你是对的,我的道具有错误。现在是工作。非常感谢你 ! –