如何在React中使用axios设置响应状态

46

我该如何在axios中设置get请求的状态?

axios.get(response){
    this.setState({events: response.data})
}
5个回答

151

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

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 时,则指向 window 对象。这就是为什么我将 this 赋值给变量 self 的原因。您可以在这里了解更多。

专业提示:

如果您使用 ES6,您会希望使用箭头函数(它们没有自己的 this),并且无需将 this 分配给变量即可使用 this.setState在这里了解更多。

    axios.get('/url')
     .then((response) => {
       console.log(response);
       this.setState({events: response.data})
     })
    .catch((error)=>{
       console.log(error);
    });

这里提供了一个完整的示例,包括常用的获取数据的最佳实践,例如错误处理、重试和加载。这可以提供更好的用户体验。鼓励您修改代码并进行尝试以获得更多内部信息。https://codesandbox.io/s/rm4pyq9m0o


1
你好,我知道我回复太晚了,但这个答案节省了我很多时间和精力。谢谢。 - Ashish Agrawal
我无法确定我的代码出了什么问题,幸运的是我偶然看到了这个答案。谢谢! - mig_08

31

这不起作用是因为axios内部的“this”与你的React组件不同。“this”在axios中指的是axios对象,而不是你的React组件。你可以使用 .bind() 来解决这个问题。

此外,axios没有被正确地使用。

应该长成这样:

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

另外,如果您使用es6,可以将该函数替换为箭头函数,而无需使用绑定(bind)即可获得相同的效果

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

3

只需尝试使用此Node.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>
    )
  }
}

-1
做类似这样的事情:
  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})
  })

-1

我以前在学习React时也遇到过类似的Promise问题。我的解决方法是将API调用放在componentDidMount方法中,并将状态设置为初始值。在数据获取期间,我使用了一个加载器。

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接