如何在axios中设置获取响应的状态?
axios.get(response){ this.setState({events: response.data}) }
您在这里遇到语法错误。你应该试试这个
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')
this
this.setState
window
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://codesandbox.io/s/rm4pyq9m0o,其中包含通常用于获取数据的 最佳实践 ,包括错误处理,重试和加载。这样可以提供 更好的用户体验 。我们鼓励您修改代码并四处探索,以获取有关它的更多见解。