如何在React中设置来自axios的响应状态 [英] How to set state of response from axios in react
问题描述
如何在axios中设置获取响应的状态?
How do I set the state of a get response in axios?
axios.get(response){
this.setState({events: response.data})
}
推荐答案
您在这里遇到语法错误.您应该试试看
You have a syntax error here. You should try this instead
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对象.您可以在此处阅读更多信息 -
this
关键字根据调用的位置而具有不同的值.this.setState
中的this
应引用构造函数对象,并且在函数内部调用this
时,它引用window
对象.这就是为什么我将this
分配给变量self
的原因.您可以在此处阅读更多信息
axios.get
is an asynchronous function which means that the rest of the code will be executed .And when the response of the server arrives, the function passed tothen
will be executed. The return value ofaxios.get('url')
is called a promise object. You can read more about it herethis
keyword has a different value depending of where it is called.this
inthis.setState
should refer to the constructor object, and when you callthis
inside a function, it refers to thewindow
object. That is why i assignedthis
to the variableself
. You can read more about this here
专业提示:
如果使用ES6,则需要使用箭头函数(没有自己的this
)并使用this.setState
而不将this
分配给变量. 在此处了解更多信息
If you use ES6, you would want to use arrow functions (which don't have their own this
) and use this.setState
without assigning this
to a variable. 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 包含最佳做法,通常用于获取数据,包括错误处理,重试和加载.这提供了更好的用户体验.我们鼓励您修改代码并四处逛逛,以获取有关它的更多见解.
Here is a complete example https://codesandbox.io/s/rm4pyq9m0o containing best practices commonly used to fetch data including error handling, try again and loading. This provides a better User experience. You are encouraged to modify the code and play around to get more insights about it.
这篇关于如何在React中设置来自axios的响应状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!