如何在反应中设置 axios 的响应状态

编程入门 行业动态 更新时间:2024-10-28 04:16:19
本文介绍了如何在反应中设置 axios 的响应状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在 axios 中设置 get 响应的状态?

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 to then will be executed. The return value of axios.get('url') is called a promise object. You can read more about it here
  • this keyword has a different value depending of where it is called. this in this.setState should refer to the constructor object, and when you call this inside a function, it refers to the window object. That is why i assigned this to the variable self. 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); });

这是一个包含 的完整示例 codesandbox.io/s/rm4pyq9m0o最佳实践常用于获取数据,包括错误处理、重试和加载.这提供了更好的用户体验.我们鼓励您修改代码并尝试获得更多有关它的见解.

Here is a complete example 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.

更多推荐

如何在反应中设置 axios 的响应状态

本文发布于:2023-10-09 16:58:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态   如何在   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!