简体   繁体   English

使用axios与react从API获取数据

[英]use axios with react to get data from api

I am trying to use axios to get data from the api ( https://reqres.in/ ) and display in my react app. 我正在尝试使用axios从api( https://reqres.in/ )获取数据并显示在我的react应用程序中。 Before this I fetched the data from the API using fetch method in javascript. 在此之前,我使用javascript中的提取方法从API提取了数据。 Now I have tried coding this from various resources. 现在,我尝试使用各种资源对此进行编码。 How should I do it. 我应该怎么做。 Is it the correct method? 这是正确的方法吗?

My app.js file- 我的app.js文件-

import React, { Component } from 'react';
import './App.css'; 
import axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
  this.successShow = this.successShow.bind(this);
  this.errorShow = this.errorShow.bind(this);
}
componentDidMount() {
 axios.get('https://reqres.in/api/products/3')
   .then(function (response) {
     this.successShow(response);
   })
   .catch(function (error) {
     this.errorShow(error);
   });
 }
successShow(response) {
 this.member = <pre>{JSON.stringify(response.data, null, '\t')}</pre> ;
}
errorShow(error) {
 this.member = <pre>{JSON.stringify(error.response.data, null, '\t')}</pre>;
}
render() {
  return (
    <div>
      <h2>Welcome to React</h2>
      <h3>{JSON.stringify(this.state.person.data)}</h3>
      <div>{this.member}</div>
    </div>
  );
  }
 }
export default App;

It also gives the error - Unhandled Rejection (TypeError): Cannot read property 'errorShow' of undefined. 它还会给出错误-未处理的拒绝(TypeError):无法读取未定义的属性'errorShow'。

Changes: 变化:

1. You need to bind this with then and catch callback methods, use arrow functions . 1.您需要将this与then绑定,并使用箭头函数捕获回调方法。

2. You didn't define the initial state and using this.state.person.data it will throw error. 2.您没有定义初始状态,使用this.state.person.data将引发错误。

3. Storing the UI in state or global variable is not a good idea, ui part should be inside render method only. 3.将UI存储在状态或全局变量中不是一个好主意,ui部分应仅在render方法内。

Write it like this: 像这样写:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            person: {}
        }
        //this.successShow = this.successShow.bind(this);
        //this.errorShow = this.errorShow.bind(this);
    }

    componentDidMount() {
        axios.get('https://reqres.in/api/products/3')
        .then((response) => {
            this.successShow(response);
        })
        .catch((error) => {
            this.successShow(error);
        });
    }

    successShow(response) {
        this.setState({
            person: response.data
        });
    }

    render() {
        return (
            <div>
              <h2>Welcome to React</h2>
              <h3>{JSON.stringify(this.state.person.data)}</h3>

              <pre>{JSON.stringify(this.state.person.data)}</pre>

              <div>{this.member}</div>
            </div>
        );
    }
}

When you call this.errorShow() inside of the function , this is not your component object, but context of function . 当您在function内部调用this.errorShow()this不是您的组件对象,而是function上下文。 You should use arrow functions instead, arrow functions do not create its own this so you can access your component this : 您应该改用箭头功能,箭头功能不会自己创建this因此您可以访问this组件:

componentDidMount() {
 axios.get('https://reqres.in/api/products/3')
   .then((response) => {
     this.successShow(response);
   })
   .catch(error) => {
     this.errorShow(error);
   });
 }

More info about arrow functions 有关箭头功能的更多信息

Try this: 尝试这个:

componentDidMount() {
 axios.get('https://reqres.in/api/products/3')
   .then((response) => {
     this.successShow(response);
   })
   .catch((error) => {
     this.errorShow(error);
   });
 }

Use arrow functions to remain the right scope of this 使用arrow functions保持的权利范围this

The problem is that the this in your then and catch callbacks doesn't refer to your class, but to the default (global) scope. 问题在于, thencatch回调中的this并不引用您的类,而是引用默认(全局)范围。 You need to bind the right this. 您需要对此进行约束。 You actually already have the appropriate functions set up with this binding, so you can just use them directly: 实际上,您已经通过此绑定设置了适当的功能,因此您可以直接使用它们:

componentDidMount() {
  axios.get('https://reqres.in/api/products/3')
   .then(this.successShow)
   .catch(this.errorShow);
}

In general, you can also use => function syntax, which inherits the 'this' from the scope the function is declared in, rather than using the global scope. 通常,还可以使用=>函数语法,该语法从声明函数的作用域继承'this',而不是使用全局作用域。 Eg 例如

componentDidMount() {
  axios.get('https://reqres.in/api/products/3')
   .then(success => this.successShow(success))
   .catch(error => this.errorShow(error));
}

(note the => functions are completely unnecessary here of course). (请注意,当然在这里完全不需要=>函数)。

You have an additional problem, which is the you need to store member in component state ( this.state.member ), not just as a field, and use the setState function to update it. 您还有另一个问题,那就是您需要将member存储在组件状态( this.state.member )中,而不仅仅是作为一个字段,然后使用setState函数对其进行更新。 Otherwise your component won't re-render when you update member . 否则,在更新member时,组件将不会重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM