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

How to set state of response from axios in react

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

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

这不起作用,因为 "this" 在 axios 内部是不同的。 "this" 里面的 axios 指的是 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 });
});

我以前在学习react的时候处理过类似的promise。我所做的是将 api 调用放在 componentDidMount 方法上并将状态设置为初始值。我在获取数据时使用了加载器。

componentDidMount() {
 const self = this;
 axios.get(response){
  self.setState({ events: response.data });
}

到目前为止,我会使用类似于 checkenrode 所说的东西。

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

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') 的 return 值称为 promise 对象。您可以阅读 more about it here
  • this 关键字具有不同的值,具体取决于调用它的位置。 this in this.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,其中包含 最佳实践 通常用于获取数据,包括错误处理、重试和加载。这提供了更好的用户体验。我们鼓励您修改代码并尝试以获得更多关于它的见解。

做这样的事情:

  var self= this; // self will now be referred to your component

  axios.get("http://localhost:3001/get_user?id=" + id)
  .then(function (response) {
    if(response.data.rows != null)
    user_detail = response.data.rows;
    console.log(response);
    self.setState({email: user_detail.name, name: user_detail.name})
  })

干脆试试这个节点js

      axios.get(`https://jsonplaceholder.typicode.com/users`)
       .then(res => {
          const persons = res.data;
          this.setState({ persons });
      })

如果你正在使用 react js 那么你首先导入组件而不是使用 axios

像这样:

import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      <ul>
        { this.state.persons.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}