2017-09-26 71 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你是對的,我的道具有錯誤。現在是工作。非常感謝你 ! –