您在这里遇到语法错误。你应该试试这个
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 prevar a = 'i might be executed before the server responds'这里有几件事要注意:
axios.get
是一个异步函数,这意味着其余代码将被执行。当服务器的响应到达时,传递给的函数then
将被执行。的返回值axios.get('url')称为承诺对象。您可以在此处了解更多信息this
关键字根据调用的位置而具有不同的值。this
inthis.setState
应该 引用构造函数对象,并且在this
函数内部调用时,它引用该window
对象。这就是为什么我分配this
给变量的原因self
。您可以在此处了解更多信息
专家提示:
如果您使用ES6,则需要使用箭头函数(没有自己的箭头函数
this),并且在
this.setState不分配
this变量的情况下使用。在这里了解更多
axios.get('/url') .then((response) => { console.log(response); this.setState({events: response.data}) }) .catch((error)=>{ console.log(error); });这是一个完整的示例https://presandbox.io/s/rm4pyq9m0o,其中包含通常用于获取数据的
最佳实践 ,包括错误处理,重试和加载。这样可以提供 更好的用户体验 。我们鼓励您修改代码并四处探索,以获取有关它的更多见解。



