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

jor*_*l88 38 javascript reactjs axios

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

axios.get(response){
    this.setState({events: response.data})
}
Run Code Online (Sandbox Code Playgroud)

Abd*_*oui 116

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

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'
Run Code Online (Sandbox Code Playgroud)

这里有几点需要注意:

  • axios.get是一个异步函数,这意味着将执行其余代码.当服务器的响应到达时,then将执行传递给的函数.返回值axios.get('url')称为promise对象.你可以在这里阅读更多相关信息
  • this关键字具有不同的值,具体取决于调用的位置.thisin this.setState 应该引用构造函数对象,当你this在函数内部调用时,它引用了window对象.这就是我分配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);
    });
Run Code Online (Sandbox Code Playgroud)

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


cec*_*ode 25

这不起作用,因为"这个"在axios内部是不同的.axios中的"this"指的是axios对象,而不是你的反应成分.您可以使用.bind解决此问题

axios也没有正确使用.

它应该看起来像

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

或者,如果使用es6,您可以为箭头函数提供函数,并在没有绑定的情况下获得相同的效果

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