2016-12-17 93 views

回答

38

這裏有一個語法錯誤。你應該試試這個代替

var self = this; 
axios.get('/url') 
.then(function (response) { 
    console.log(response); 
    self.setState({events: response.data}) 
}) 
.catch(function (error) { 
    console.log(error); 
}); 
//the rest of the code 
var a = 'i might be executed before the server responds' 

有幾件事情,這裏要注意:

  • axios.get是一個異步功能,這意味着其餘代碼會被執行。而當的響應服務器到達,傳遞給then的函數將被執行。 axios.get('url')的返回值稱爲承諾對象。您可以閱讀more about it here
  • this關鍵字具有不同的值,具體取決於它的調用位置。 this in this.setState應該指的是構造函數對象,當你在函數內部調用this時,它指的是window對象。這就是爲什麼我將this分配給變量self。您可以閱讀more about this here

臨提示:

如果使用ES6,你可能需要使用箭頭功能(不擁有自己的this),並使用this.setState不分配this給一個變量。 more about it here

axios.get('/url') 
    .then((response) => { 
     console.log(response); 
     this.setState({events: response.data}) 
    }) 
    .catch((error)=>{ 
     console.log(error); 
    }); 
+1

這就是我最後做了。 – Ksenia

+1

這是正確的答案,謝謝@abdellah – Dipesh

14

這不起作用,因爲「this」在axios內部不同。 axios中的「this」是指axios對象,而不是你的反應組件。您可以使用.bind來解決此問題

另外axios沒有正確使用。

它應該是這個樣子

axios.get("/yourURL").then(function(response) { 
    this.setState({ events: response.data }); 
}.bind(this)); 

另外,如果使用ES6你能分出來的功能箭頭功能並獲得相同的效果,而不綁定

axios.get("/yourURL").then(response => { 
    this.setState({ events: response.data }); 
}); 
0

我處理過類似的承諾在過去,當我學習反應的時候。我所做的是將API調用放在componentDidMount方法上,並將狀態設置爲初始值。數據被提取時我使用了一個加載器。

componentDidMount() { 
const self = this; 
axios.get(response){ 
    self.setState({ events: response.data }); 
} 

截至目前,我會用類似於checkenrode的說法。

0

做這樣的事情:

var self= this; // self will now be referred to your component 

    axios.get("http://localhost:3001/get_user?id=" + id) 
    .then(function (response) { 
    if(response.data.rows != null) 
    user_detail = response.data.rows; 
    console.log(response); 
    self.setState({email: user_detail.name, name: user_detail.name}) 
    })