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

新手上路,请多包涵

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

 axios.get(response){
    this.setState({events: response.data})
}

原文由 jordanpowell88 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 517
2 个回答

你这里有语法错误。你应该试试这个

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 in this.setState should refer to the constructor object, and when you call this inside a function, it refers to the window object.这就是为什么我将 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://codesandbox.io/s/rm4pyq9m0o ,其中包含通常用于获取数据的 最佳实践,包括错误处理、重试和加载。这提供了 更好的用户体验。我们鼓励您修改代码并尝试以获得更多关于它的见解。

原文由 Abdellah Alaoui 发布,翻译遵循 CC BY-SA 3.0 许可协议

这不起作用,因为“this”在 axios 内部是不同的。 axios 中的“this”指的是 axios 对象,而不是你的反应组件。您可以使用 .bind 解决此问题

axios 也没有被正确使用。

它应该看起来像

axios.get("/yourURL").then(function(response) {
  this.setState({ events: response.data });
}.bind(this));

或者,如果使用 es6,则可以将函数分出为箭头函数,无需绑定即可获得相同的效果

axios.get("/yourURL").then(response => {
  this.setState({ events: response.data });
});

原文由 ceckenrode 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题