javascript - 如何在react中设置axios的响应状态

标签 javascript reactjs axios

如何在 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关键字根据调用位置的不同而具有不同的值。 thisthis.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/

相关文章:

javascript - jQuery:自动完成多个ajax请求

javascript - 有没有办法在 react 组件的表格上添加边框?

css - React Native - 操纵 View 以将阴影应用于图像的 BorderRadius?

reactjs - TypeError : data. map 不是函数,但 data 是数组

reactjs - AXIOS 请求方法更改为 'OPTIONS' 而不是 'GET'

javascript - 使用复选框显示隐藏表

javascript - Ember js 如何强制重新加载特定的选定记录?

javascript - 如何从都驻留在 React 组件上的函数调用函数

javascript - 避免删除子表正在使用的父表数据

javascript - CategoryFilter 作为列选择器