[英]use axios with react to get data from api
我正在尝试使用axios从api( https://reqres.in/ )获取数据并显示在我的react应用程序中。 在此之前,我使用javascript中的提取方法从API提取了数据。 现在,我尝试使用各种资源对此进行编码。 我应该怎么做。 这是正确的方法吗?
我的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;
它还会给出错误-未处理的拒绝(TypeError):无法读取未定义的属性'errorShow'。
变化:
1.您需要将this
与then绑定,并使用箭头函数捕获回调方法。
2.您没有定义初始状态,使用this.state.person.data
将引发错误。
3.将UI存储在状态或全局变量中不是一个好主意,ui部分应仅在render方法内。
像这样写:
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>
);
}
}
当您在function
内部调用this.errorShow()
, this
不是您的组件对象,而是function
上下文。 您应该改用箭头功能,箭头功能不会自己创建this
因此您可以访问this
组件:
componentDidMount() {
axios.get('https://reqres.in/api/products/3')
.then((response) => {
this.successShow(response);
})
.catch(error) => {
this.errorShow(error);
});
}
尝试这个:
componentDidMount() {
axios.get('https://reqres.in/api/products/3')
.then((response) => {
this.successShow(response);
})
.catch((error) => {
this.errorShow(error);
});
}
使用arrow functions
保持的权利范围this
问题在于, then
和catch
回调中的this
并不引用您的类,而是引用默认(全局)范围。 您需要对此进行约束。 实际上,您已经通过此绑定设置了适当的功能,因此您可以直接使用它们:
componentDidMount() {
axios.get('https://reqres.in/api/products/3')
.then(this.successShow)
.catch(this.errorShow);
}
通常,还可以使用=>
函数语法,该语法从声明函数的作用域继承'this',而不是使用全局作用域。 例如
componentDidMount() {
axios.get('https://reqres.in/api/products/3')
.then(success => this.successShow(success))
.catch(error => this.errorShow(error));
}
(请注意,当然在这里完全不需要=>
函数)。
您还有另一个问题,那就是您需要将member
存储在组件状态( this.state.member
)中,而不仅仅是作为一个字段,然后使用setState
函数对其进行更新。 否则,在更新member
时,组件将不会重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.