2016-12-17 162 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}) 
    })