如何在 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')
被称为 promise 对象。您可以阅读more about it here -
this
关键字根据调用位置的不同而具有不同的值。this
在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);
});
这是一个完整的示例 https://codesandbox.io/s/rm4pyq9m0o包含通常用于获取数据的最佳实践,包括错误处理、重试和加载。这提供了更好的用户体验。我们鼓励您修改代码并尝试一下以获得更多关于它的见解。
关于javascript - 如何在react中设置axios的响应状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41194866/